我正在使用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”
}
]
}
}
我可以采取什么方法来实现这一目标?是否可以自定义对象反序列化的方式?
答案 0 :(得分:1)
我知道您要求在反序列化中完成此操作,但这会产生相同的结果。 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;}
}