1

I got a JSON string with an array like this:

 {
  "Id": 123,
  "Username": "Sr. X",
  "Packages": [
    {
      "Name": "Cups",
      "SupplierId": 1,
      "ProviderGroupId": 575,
      "SupplierName": "Foo Cups"
    },
    {
      "Name": "Pins",
      "SupplierId": 5,
      "ProviderGroupId": 1082,
      "SupplierName": "Foo Pins"
    }
  ]
}

and I want to add a new field into Packages array like:

"Packages": [
    {
      "Name": "Cups",
      "SupplierId": 1,
      "ProviderGroupId": 575,
      "SupplierName": "Foo Cups",
      "New Field": "Value"
    },...

Right now I can add a new field but in the main object, I'm using Json.NET library to do the job, but it seems that the documentation doesn't reach that level.

Have any one of you done it before?

3
  • Can you not just serialize the "main object" again with JsonConvert.SerializeObject(); after adding the new object to the collection? Commented Sep 9, 2016 at 17:08
  • 2
    What exactly are you trying to do? The Json.NET documentation is pretty clear about how to add properties to JObjects... Commented Sep 9, 2016 at 17:16
  • I'm receiving a string with a JSON structure (the first snippet) but what I want is to add a new field and value to it, to then parse it to a xml, but that part I have done it already Commented Sep 9, 2016 at 17:27

2 Answers 2

4

JObject implemets IDictionary.

var jObj = JObject.Parse(json);
foreach(var item in jObj["Packages"])
{
    item["New Field"] = "Value";
}
var newjson = jObj.ToString(Newtonsoft.Json.Formatting.Indented);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer L.B. that worked. Is haven't worked with JSON before and I thought it was about time so I started to practicing, now I know a little bit more.
-1

Try

JObject root = (JObject) JsonConvert.DeserializeObject(File.ReadAllText("products.json"));
JArray packages = (JArray) root["Packages"];

JObject newItem = new JObject();
newItem["Name"] = "Cups";
// ...

packages.Add(newItem);

Console.WriteLine(root); // Prints new json

1 Comment

Thanks for the answer but LB approach worked for me. Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.