Nick_F
Nick_F

Reputation: 1117

Add new record in json

I want to add a new record to the json collection:

{
    "type": "FeatureCollection",
    "features": [
    {
        "type": "Feature",
        "id": 1,
        "name": "Location1",
        "geometry": {
        "type": "Point",
            "coordinates": [
                 150.74379,
                 -30.280119
            ]
         }
    },
    {
        "type": "Feature",
        "id": 2,
        "name": "Location2",
        "geometry": {
           "type": "Point",
           "coordinates": [
                 148.387392,
                 -23.781484
           ]
         }
    }]
}

and I want to find what is the best way to create such an object and to insert it. So far I added the code below, which raises an error

Can not add Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JObject.

when I want to add the new object to the array

var array = JsonConvert.DeserializeObject<dynamic>(json);

dynamic jsonObject = new JObject(); // needs using Newtonsoft.Json.Linq;
jsonObject.type = "feature";
jsonObject.id = 3;
jsonObject.name = sAddress;
jsonObject.type = "Point"; 
jsonObject.coordinates = "12, 13";

array.Add(jsonObject); // error Can not add Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JObject.

Upvotes: 1

Views: 2255

Answers (1)

Nkosi
Nkosi

Reputation: 247531

The variable you call array is not an array based on the json above. The array is in the features property. You would have to do array.features.Add(jsonObject); to get your above code to work.

Like

var rootObject = JsonConvert.DeserializeObject<dynamic>(json);

dynamic feature = new JObject();
feature.type = "Feature";
feature.id = 3;
feature.name = sAddress;

dynamic geometry = new JObject();
geometry.type = "Point"; 
geometry.coordinates = new JArray(12, 13);

feature.geometry = geometry;

rootObject.features.Add(feature);

Upvotes: 2

Related Questions