Reputation: 509
Is there a way i can merge these JSON:
JSON 1
{
"items": [{
"date": "2018-08-25",
"id": 1,
"name": "John"
}]
}
JSON 2
{
"items": [{
"date": "2018-08-25",
"id": 1,
"age": 20,
"address": "USA",
"Weight": "256 kg"
}]
}
RESULT
{
"items": [{
"date": "2018-08-25",
"id": 1,
"name": "John",
"age": 20,
"address": "USA",
"Weight": "256 kg"
}]
}
Note that I want to merge JSON items which has the same id as the bearing. Can this be achieved ? Thank you for your feedback
Upvotes: 0
Views: 1038
Reputation: 46219
You can try to create some object for json1 and json2 data format.
public class Item1
{
public string date { get; set; }
public int id { get; set; }
public string name { get; set; }
}
public class Object1
{
public List<Item1> items { get; set; }
}
public class Item2
{
public string date { get; set; }
public int id { get; set; }
public int age { get; set; }
public string address { get; set; }
public string Weight { get; set; }
}
public class Object2
{
public List<Item2> items { get; set; }
}
public class Item
{
public string date { get; set; }
public int id { get; set; }
public string name { get; set; }
public int age { get; set; }
public string address { get; set; }
public string Weight { get; set; }
}
public class Result
{
public List<Item> items { get; set; }
}
and use DeserializeObject
get object data from json string.
Object1 obj1 = JsonConvert.DeserializeObject<Object1>(Json1);
Object2 obj2 = JsonConvert.DeserializeObject<Object2>(Json2);
then use linq join to create the result list.
var resultList = (from o1 in obj1.items
join o2 in obj2.items on o1.id equals o2.id
select new Item()
{
id = o1.id,
date = o1.date,
address = o2.address,
age = o2.age,
name = o1.name,
Weight = o2.Weight
}).ToList();
final use SerializeObject
transform Result
to result json.
string jsonResult = JsonConvert.SerializeObject(new Result() { items = resultList });
EDIT
If you want to avoid create too many class, you can try to use JObject.Parse
linq join
on JToken
dictionary, so you didn't need to create the object class to carry JSON data.
var obj1 = JObject.Parse(Json1);
var obj2 = JObject.Parse(Json2);
var resultList = (from o1 in obj1["items"]
join o2 in obj2["items"] on o1["id"] equals o2["id"]
select new Item()
{
id = o1["id"].ToObject<int>(),
date = o1["date"].ToObject<string>(),
address = o2["address"].ToObject<string>(),
age = o2["age"].ToObject<int>(),
name = o1["name"].ToObject<string>(),
Weight = o2["Weight"].ToObject<string>()
}).ToList();
JsonConvert.SerializeObject(new Result() { items = resultList });
string jsonResult = JsonConvert.SerializeObject(new Result() { items = resultList });
Result
{
"items":[
{
"date":"2018-08-25",
"id":1,
"name":"John",
"age":20,
"address":"USA",
"Weight":"256 kg"
}
]
}
Upvotes: 3
Reputation: 462
{
"date": "2018-08-25",
"id": 1,
"name": "John"
}
It can be deserialize to a Dictionary<string, object>
Upvotes: -1