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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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);

posted @   LoveCoder  阅读(6275)  评论(5编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示