[英]Remove the “{}” from the json data generated using 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.Parse(json)
); 通過在遍歷時更新嵌套的 JObjects 來修改對象圖; 序列化現在表示修改后的對象圖的原始 JObject。或者
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.