Reputation: 10190
I have a pair of classes that look something like this:
public class Parent
{
public int id { get; set; }
public string name { get; set; }
public List<Child> children { get; set; }
}
public class Child
{
public int id { get; set; }
public string name { get; set; }
}
In order to populate the parent class, I make an API call and deserialize the returned JSON which looks like this:
JSON
{
“parent”:{
“id”:”123”,
“name”:”parent name”,
“child”:{
“id”:”456″
},
}
}
C#
var parent = new JavaScriptSerializer().Deserialize<List<Parent>>(jsonString);
I then use the id
of the child
to make another API call which returns more details about the child
that I need to use to populate the parent
:
{
“child”:{
“id”:”456”,
“name”:”child name”
}
}
How can I populate the rest of the Parent
class with the data from the child
JSON string?
Upvotes: 0
Views: 331
Reputation: 101643
If I understood correctly, all you need is just make request for every partial child from Parent.children
and then replace whole collection with full children information:
var parents = new JavaScriptSerializer().Deserialize<List<Parent>>(jsonString);
foreach (var parent in parents) {
var fullChildren = new List<Child>();
foreach (var partialChild in parent.children) {
var fullChild = GetChildJsonById(partialChild.id);
fullChildren.Add(fullChild);
}
// just replace whole stuff
parent.children = fullChildren;
}
Upvotes: 2
Reputation: 511
I haven't tested this, but I am fairly certain you can do something like:
var child = new JavaScriptSerializer().Deserialize<Child>(jsonString);
There shouldn't be more to it than that, assuming all you want is to update your child class.
This seems inefficient though, I don't know why the full child object isn't given from the first api call.
Upvotes: 0