Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add property to each object in JSON C#

I have a JSON body which looks like this(an array of objects):

[
    {
        "registered": "2016-02-03T07:55:29",
        "color": "red",
    },
    {
        "registered": "2016-02-03T17:04:03",
        "color": "blue",
    }
]

This body is contained in a variable(requestBody) I create based on a HTTP Request, it’s called req:

string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

What I want to do is add a unique identifier to each one of the objects in my JSON array. How could I go about achieving this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Currently I am deserializing the JSON, adding some string(x) to it and then serializing it again:

dynamic d = JsonConvert.DeserializeObject(requestBody);
d.uniqueId = "x";
string newBody = JsonConvert.SerializeObject(d);

I was to add a uniqueId to each one of the objects in my JSON array of objects. How could I achieve this?

>Solution :

You can use JArray from LINQ to JSON API to parse, iterate children of JObject type and modify them:

var json = ...; // your json string
var jArray = JArray.Parse(json);
foreach (var jObject in jArray.Children<JObject>())
{
    jObject.Add("id", new JValue("x"));
}
var modified = JsonConvert.SerializeObject(jArray);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading