sandunes90
sandunes90

Reputation: 473

JSON.NET Add sub property to propert

I'm trying to modify a JSON string where I want to add a sub property to a property.

Original JSON:

{
    "main_table": [{
        "id_no": 1,
        "alt_id": 2
    }]
}

Desired JSON:

   {
        "main_table": [{
            "id_no": 1,
            "alt_id": {
                "alt_id": 2,
                "sub_id2": 30
            }
        }]
    }

This is how I'm trying to achieve this -

Method 1:

var jTable = (JObject)jsonO["main_table"].FirstOrDefault();                
if (jTable != null)
{
  var jProp = jTable.Property(colToModify);
  jTable.Remove();
  jTable.Add(new JProperty("alt_id", new JProperty[] 
  { new JProperty("alt_id", "2"), new JProperty("sub_id2", "30")}
  ));
}

I get the error "Can not add Newtonsoft.Json.Linq.JProperty to Newtonsoft.Json.Linq.JArray.".

Upvotes: 0

Views: 474

Answers (1)

Andrew Williamson
Andrew Williamson

Reputation: 8671

You need to add a JObject to the array, not a JProperty. Try something like the following:

jTable.Add(
    new JObject(
        new JProperty("alt_id", new JObject(
            new JProperty("alt_id", "2"),
            new JProperty("sub_id2", "30")
        )
    )
);

Upvotes: 1

Related Questions