I have an object model as below, some of the objects have zero or more relationships
public class Foo
{
public string Id
public string Name
}
public class Bar
{
public string Id
public Foo Foo
public DateTime At
}
public class Baz
{
public string Id
public DateTime At
public List<Bar> Bars
}
public class Qux
{
public string Id
public string Name
public List<Baz> Baz
}
I need to deserialize the following 4 json files.
Foo.json
[
{
"Id": "1",
"Name": "AAA"
},
{
"Id": "2",
"Name": "BBB"
}
]
Bar.json
[
{
"Id": "1",
"FooId": "1",
"BazId": "1",
"At": "2022-01-01T10:00:00"
},
{
"Id": "2",
"FooId": "2",
"BazId": "1",
"At": "2022-01-02T10:00:00"
}
]
Baz.json
[
{
"Id": "1",
"Quxd": "1",
"At": "2022-01-01T10:00:00"
},
{
"Id": "2",
"QuxId": "1",
"At": "2022-01-02T10:00:00"
}
]
Qux.Json
[
{
"Id": "1",
"Name": "CCC"
},
{
"Id": "2",
"Name": "DDD"
}
]
I know it is a badly designed JSON file and I cannot change that and that is my challenge to resolve it without changing the json.
I was able to solve the issue, by creating another 4 sets of objects for each JSON and deserializing them individually, after that, I will have a loop for object4 to map all other objects.
But I feel it is not that efficient.
Please let me know if you have any other ideas so that I can solve this in a much better way.
Thanks
CodePudding user response:
I think another way could be to merge json files and then just deserialise them to classes:
JObject o1 = JObject.Parse(@"{
'FirstName': 'John',
'LastName': 'Smith',
'Enabled': false,
'Roles': [ 'User' ]
}");
JObject o2 = JObject.Parse(@"{
'Enabled': true,
'Roles': [ 'User', 'Admin' ]
}");
o1.Merge(o2, new JsonMergeSettings
{
// union array values together to avoid duplicates
MergeArrayHandling = MergeArrayHandling.Union
});
When you have merged arrays, then you can use this beautiful tool to create model classes by json file. Converting json to C#
CodePudding user response:
This is badly formatted json, so please ignore