我有json数据,它来自API。 json的结构就像这样
{
"data": [
{
"nameid": "s_10",
"size": "6.46",
"name": "abc",
"children": [
{
"nameid": "i_101010",
"size": "8.84",
"name": "bcd",
"children": [
{
"nameid": "si_10101010",
"size": "4.00",
"name": "efg",
"children": [
{
"nameid": "c_3273",
"size": 4,
"name": "ttt",
}
]
},
{
"nameid": "si_10101020",
"size": "13.67",
"name": "sss",
"children": [
{
"nameid": "c_4450",
"size": 1,
"name": "rrr",
},
{
"nameid": "c_551",
"size": 17,
"name": "ddd",
},
我需要将其转换为类似下面的结构
{
"id": 1,
"parentId": "NULL",
"name": "Root",
"size": 5,
"children": [
{
"id": 10,
"parentId": "1",
"name": "En",
"size": 1,
"children": [
{
"id": 1010,
"parentId": "10",
"name": "Eee",
"size": 1,
"children": [
{
"id": 101010,
"parentId": "1010",
"name": "Enh",
"size": 5,
"children": [
{
"id": 10101010,
"parentId": "101010",
"name": "Ooo",
"size": 5
},
所以简而言之,我需要将该字段的父ID添加到第一个JSON
注意:这些是部分数据,因此json可能不是有效数据。
答案 0 :(得分:0)
如果你的源和目标对象是Typed Class(例如公共类 FamilyMembers )
Automapper是实现这一目标的最佳方式。
假设您的来源'数据'是家庭类。您可以将家庭映射到 FamilyMembers
//specify source, destination
Mapper.CreateMap<Families, FamilyMembers>();
//get source data
Families families = GetFamiliesFromAPI();
//map each properties of families to familymembers
FamilyMembers familymembers = Mapper.Map<Families, FamilyMembers>(families);
ShowFamilyMembersInDataGrid(familymembers);
如果您不想使用Automapper,请使用LINQ
Families families = GetFamiliesFromAPI();
families.Select(f => f, new FamilyMembers() {name = f.Name, someProperty = f.someProperty }
由于你有嵌套的JSON对象,你需要学习如何处理源数据中的“children”成员,并通过LINQ相应地映射