user2329820
user2329820

Reputation: 1

Add JObject to another JObject in .NET

I have two JObject's loaded from the following two JSON files:

{
  "data": {
    "organism": {
      "human": [
        {
          "firstName": "John",
          "lastName": "Doe"
        }
      ]
    }
  }
}
{
  "degrees": [
    {
      "type": "bachelor",
      "major": "Math"
    },
    {
      "type": "master",
      "major": "Computer Science"
    }
  ]
}

I want to combine them into one JObject like this:

{
  "data": {
    "organism": {
      "human": [
        {
          "firstName": "John",
          "lastName": "Doe",
          "degrees": [
            {
              "type": "bachelor",
              "major": "Math"
            },
            {
              "type": "master",
              "major": "Computer Science"
            }
          ]
        }
      ]
    }
  }
}

I have tried to add them as new field like this, but I am getting an error that i can't add JObject to another JObject:

jObject1["data"]["organism"]["human"][0]["lastName"].Parent.AddAfterSelf(jObject2)

I then tried to add it using JProperty but it just added a duplicate field which is not the format I need.

jObject1["data"]["organism"]["human"][0]["lastName"].Parent.AddAfterSelf(new JProperty("degrees",jobject2))

I am not sure how to proceed from this.

Upvotes: 0

Views: 984

Answers (1)

dbc
dbc

Reputation: 117036

You can do this as follows:

((JObject)jObject1["data"]["organism"]["human"][0]).Add(jObject2.Property("degrees"));

Notes:

  • Casting the return of jObject1["data"]["organism"]["human"][0] to JObject ensures there really is a JSON object at that path. Assuming the cast can be made, properties can be added easily.

  • Your query adds an additional term ["lastName"], which essentially selects the JValue "Doe" corresponding to "lastName": "Doe". Not sure why you are doing that, so I removed it from my solution.

  • JObject.Property returns the JProperty with the given name, or null if not found. That JProperty can then be added to another JObject via its Add() method. Note that, in fact, a clone of the selected property is added, see this answer to JArray.Remove(JToken) does not delete for why.

Demo fiddle here.

Upvotes: 2

Related Questions