Dryden Long Dryden Long - 9 months ago 110
JSON Question

C# - Add Second JSON string to existing class

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?

Evk Evk
Answer Source

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;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download