簡體   English   中英

使用 newtonsoft 從 Json 字符串中刪除屬性

[英]Remove Properties From a Json String using newtonsoft

我有以下 JSON 字符串:

{  
   "results":[  
      {  
         "id":11,
         "name":"Employee A",
         "isEmployee":true
      },
      {
         "id":12,
         "name":"Employee B",
         "isEmployee":true
      },
      {
         "id":13,
         "name":"Employee C",
         "isEmployee":true
      },
      {
         "id":14,
         "name":"Contractor A",
         "isEmployee":false
      },
      {
         "id":15,
         "name":"Contractor B",
         "isEmployee":false
      }
   ],
   "totalItems":5
}

我需要從中刪除 id 和 isEmployee 屬性,只留下 name 屬性。

這是想要的結果:

{  
   "results":[  
      {  
         "name":"Employee A"
      },
      {  
         "name":"Employee B"
      },
      {  
         "name":"Employee C"
      },
      {  
         "name":"Contractor A"
      },
      {  
         "name":"Contractor B"
      }
   ],
   "totalItems":5
}

如何使用 Newtonsoft JSON.NET 在 C# 中完成此操作?

有一個 Remove 方法存在(不確定它是否在這個問題的時間)

例如:

var raw = "your json text";
var o = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(raw);
o.Property("totalItems").Remove()
return o.ToString();

或為您的確切輸入

var parent = JsonConvert.DeserializeObject<JObject>(raw);
((JArray)parent.Property("results").Value)
    .Select(jo => (JObject)jo)
    .ToList()
    .ForEach(x => 
        x
            .Properties()
            .ToList()
            .ForEach(p =>
            {
                if (p.Name != "name")
                    p.Remove();
            }))
    //.Dump();
    ;

有兩種基本方法,

任何一個

  • 將其解析為 JObject(例如JObject.Parse(json) ); 通過在遍歷時更新嵌套的 JObjects 來修改對象圖 序列化現在表示修改后的對象圖的原始 JObject。

或者

  • 將 JSON 反序列化為強類型對象,無需附加屬性。 C# 類型中不存在的屬性將被靜默刪除。 然后序列化剛剛反序列化的對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM