我正在使用 Json.NET 将传入的 json 数据反序列化为对象,但我想将其中一个嵌套数据作为数组展平到属性中。
我传入的 json 数据是什么样的:
{
“sets": {
"set": [
{
"name": "Act 1:",
“title”: [
{
"name": “A”
},
{
"name": “B”
},
{
"name": “C”
},
{
"name": “D”
}
]
},
{
"name": "Act 2:",
“title”: [
{
"name": “E”
},
{
"name": “F”
},
{
"name": “G”
}
]
}
]
}
}
当对象被序列化时,我希望转换后的数据看起来像这样:
{
“sets": {
“title”: [
{
"name": “A”
},
{
"name": “B”
},
{
"name": “C”
},
{
"name": “D”
},
{
"name": “E”
},
{
"name": “F”
},
{
"name": “G”
}
]
}
}
我可以采取什么方法来实现这一目标?是否可以自定义我的对象的反序列化方式?
最佳答案
我知道您要求在反序列化中完成它,但这会产生相同的结果。 https://dotnetfiddle.net/U89KwW
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
public class Program
{
public const string Json = "{\"sets\": {\"set\": [{\"name\": \"Act 1:\",\"title\": [{\"name\":\"A\"},{\"name\": \"B\"},{\"name\": \"C\"},{\"name\": \"D\"}]},{\"name\": \"Act 2:\",\"title\": [{\"name\": \"E\"},{\"name\": \"F\"},{\"name\": \"G\"}]}]}}";
public static void Main()
{
Something something = JsonConvert.DeserializeObject<Something>(Json);
something.Titles = something.sets.set.SelectMany(c=> c.title).ToList();
something.sets = null;
string JsonResult = JsonConvert.SerializeObject(something);
Console.WriteLine(JsonResult);
}
}
public class Something
{
public Sets sets {get;set;}
public List<Title> Titles {get;set;}
}
public class Sets
{
public List<Set> set {get;set;}
}
public class Set
{
public string name {get;set;}
public List<Title> title {get;set;}
}
public class Title
{
public string name {get;set;}
}
关于c# - 如何将嵌套 JSON 数据反序列化为扁平对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57015544/