码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2018-12-06 20:24:25      阅读:318      评论:0      收藏:0      [点我收藏+]

标签:script   ati   prope   sof   type   retain   err   排除   rip   

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);

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

标签:script   ati   prope   sof   type   retain   err   排除   rip   

原文地址:https://www.cnblogs.com/Jerseyblog/p/10078278.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!