Reputation: 33
I have a question regarding supplying data to class instances. So I have two json files with daily data which I ultimately need to have as one class instance (for ease of later use):
Json 1:
{id:1,days:[{day:1,data1:blah!, data2:blah2, data3:blah3},{day:2,data1:blah!, data2:blah2, data3:blah3},{day:3,data1:blah!, data2:blah2, data3:blah3]}
Json2:
{id:1,days:[{day:1,data4:blah!, data5:blah2, data6:blah3},{day:2,data4:blah!, data5:blah2, data6:blah3},{day:3,data4:blah!, data5:blah2, data6:blah3}]}
And I have class
public class rootObject
{
public int id {get; set;}
public Days[] data {get; set;}
}
public class Days
{
public Datetime day {get; set;}
public string data1 {get; set;}
public string data2 {get; set;}
public string data3 {get; set;}
public string data4 {get; set;}
public string data5 {get; set;}
public string data6 {get; set;}
}
I am using
rootObject myData = JsonSerializer.Deserialize<rootObject>(json1);
which nicely provides half the data.
What I need now is to add the data from the second file, while matching the dates, to the same myData so I can have one object from which I can later pull all fields at once.
Currently I'm creating a second myData2 with data from second Json and then I use nested loop with if to combine them:
foreach(Day x in myData.data){
foreach(Day y in myData2.data){
if(x.day == y.day){
x.data4 = y.data4
// (and so on)
}
}
}
Event though the above works I use this quite a lot and it make the code a mess. There has to be a quicker and more elegant way to do this.
Upvotes: 0
Views: 940
Reputation: 5402
I'm not sure I understand your choice of representing two distinct data sets as a single class, but then again I'm not getting the full picture. If what you're trying to achieve is an informed choice, Newtonsoft.Json
has methods for merging two JSONs (though you have to use the untyped JObject
approach and convert to typed after merging). You could do something like the following:
var first = JObject.Parse(jsonString1);
var second = JObject.Parse(jsonString2);
var merged = new JObject();
merged.Merge(first);
merged.Merge(second);
var result = merged.ToObject<YourAggregatedClass>();
Upvotes: 0