0

I have this JSON:

{
  "ID":123,
  "Products":null,
  "Title":"Products"
}

I want to add some data from DB to the "Products" node so my final json will look like so:

{
  "ID":123,
  "Products":[
      {
        "ID":1,
        "Name":"AA"
      },
      {
        "ID":2,
        "Name":"BB"
      }
    ],
  "Title":"Products"
}

I'm using this code:

internal class Product
{
    public int ID { get; set; }
    public string Name { get; set; }
}

//simulate DB
var products= new List<Product>()
{
    new Product() {ID=1,Name="AA" },
    new Product() {ID=2,Name="BB" }
};

string JSONstr = FilesUtils.OpenFile(Path.Combine(Environment.CurrentDirectory, "Sample.json"));
JObject JSON = JObject.Parse(JSONstr);
        ((JValue)JSON["Products"]).Value = JObject.FromObject(products); 

But I get an exception:

Object serialized to Array. JObject instance expected.

DerApe
  • 3,097
  • 2
  • 35
  • 55
Izikon
  • 902
  • 11
  • 23

2 Answers2

1

You can do:

JSON["Products"] = JToken.FromObject(products);

To add a new property, do the same thing, e.g.:

JSON["TimeStamp"] = JToken.FromObject(DateTime.UtcNow);

Notes:

  • The item setter for JObject will add or replace the property with the specified name "Products".

  • JToken.FromObject() serializes any .Net object to a LINQ to JSON hierarchy. JToken is the abstract base class of this hierarchy and so can represent both arrays, objects, and primitives. See here for details.

Sample fiddle.

dbc
  • 104,963
  • 20
  • 228
  • 340
0

The expected object will have to be (according to your JSON). If that's the JSON you want you might consider wrapping it up and adding the ID and a Title as shown in the JSON.

public class Product
{
    public int ID { get; set; }
    public string Name { get; set; }
}

public class YourObject
{
    public int ID { get; set; }
    public List<Product> Products { get; set; }
    public string Title { get; set; }
}
Felix Av
  • 1,254
  • 1
  • 14
  • 22