I have a couple JObjects that are being returned from different places but that have all the same properties. I need to concatenate/merge this into one larger jObject. Is this possible and how would I go about doing it?
I want it to have all the same proerties as the individual objects. For instance.
jObject1 = { "data": [{"name": "foo","id": "1234" }]};
jObject2 = {"data": [{ "name": "foo2", "id": "5678" }]};
Resulting in something like this.
jobject3 = { "data": [{ "name": "foo", "id": "1234"}, { "name": "foo2", "id": "5678" }]};
I’m coding in C# and the only thing I have thought about doing so far is something like this which isn’t valid. Not really sure how to begin and can’t really anything.
jobject3 = jObject1.Concat(jObject2);
I am trying to manually loop through each object and build a new object. I think I am close but keep getting an error when adding the second item (oAlldepartment.Add) saying “Can not add property to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.”.
dynamic dynObj = JsonConvert.DeserializeObject(people);
foreach (var item in dynObj.data)
{
string id = item.id;
string name = item.name;
department = getdepartment(id);
JObject oDepartment = new JObject();
try
{
if (!String.IsNullOrEmpty(department))
oDepartment = JObject.Parse(department);
}
catch (Exception ex)
{
}
JArray departmentArray = new JArray();
if (oDepartment != null)
{
foreach (var x in oDepartment["data"].Children())
{
try
{
JObject departmentObject = new JObject();
((JObject)departmentObject).Add(new JProperty("name", x["name"]));
((JObject)departmentObject).Add(new JProperty("department", new JObject(new JProperty("name", x["department"]["name"]))));
((JObject)departmentObject).Add(new JProperty("hire_date", x["hire_date"]));
((JObject)departmentObject).Add(new JProperty("description", x["description"]));
departmentArray.Add(departmentObject);
}
catch (Exception ex)
{
}
((JObject)x).Add(new JProperty("itemtype", "post"));
}
try
{
oAlldepartment.Add(new JProperty("", new JArray(departmentArray)));
}
catch (Exception ex)
{
}
}
}
Thanks,
Rhonda
What I ended up doing was creating a class that defined the json I wanted to return and adding the json properties from each indivual object. The other benefit is my data returned by the method to the client is cleaner as I only have to worry about the properties I need instead of a huge json object with a bunch of properties that I don’t need.
Rhonda