Newtonsoft.Json 序列化 排除指定字段或只序列化指定字段


using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for LimitPropsContractResolver
/// </summary>
public class LimitPropsContractResolver : DefaultContractResolver
{
    string[] props = null;

    bool retain;

    /// <summary>
    /// 構造函數
    /// </summary>
    /// <param name="props">傳入的屬性數組</param>
    /// <param name="retain">true:表示props是需要保留的字段  false:表示props是要排除的字段</param>
    public LimitPropsContractResolver(string[] props, bool retain = true)
    {
        //指定要序列化屬性的清單
        this.props = props;

        this.retain = retain;
    }

    protected override IList<JsonProperty> CreateProperties(Type type,

    MemberSerialization memberSerialization)
    {
        IList<JsonProperty> list =
        base.CreateProperties(type, memberSerialization);
        //只保留清單有列出的屬性
        return list.Where(p =>
        {
            if (retain)
            {
                return props.Contains(p.PropertyName);
            }
            else
            {
                return !props.Contains(p.PropertyName);
            }
        }).ToList();
    }
}

  調用代碼:

var jSetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
string[] props = { "operationRemark", "managerCode", "checkRemark" }; //排除掉,不能讓前端看到的字段。為true的話就是只保留這些字段
jSetting.ContractResolver = new LimitPropsContractResolver(props, false);

jsonStr = JsonConvert.SerializeObject(slboe, jSetting);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM