Home > Mobile >  Add anonymous or an object properties to JObject in C#
Add anonymous or an object properties to JObject in C#

Time:10-29

I have following class

public class Customer{
  public string name {get;set;}
  public JObject properties {get;set;} = new JObject();
}

Now I am adding properties to customer properties

var customer = new Customer();

customer.properties["wow-123:test"] =  new { 
    name = "Mark, 
    company = new  { 
            name = "LLC",
            address = new  {
city= "London" } } }

In the end I want this to look like:

    "properties": {
      "wow-123:test": [
        {
          "name": "Mark",
          "company": {
            "name": "LLC",
            "address ": {
              "city": "London"
            }
          }
        }
      ]
    }

I keep getting error that it cannot convert it to Jtoken. If I change it to ToString then it is not in JSON format. How can I achieve the above?

CodePudding user response:

First, you need to explicitly convert your anonymously typed object to a JToken:

customer.properties["wow-123:test"] = JToken.FromObject(new { ... });

However, since your example output shows that the contents of wow-123:test are an array (..."wow-123:test": [ { "name":...) , what you actually need might be

customer.properties["wow-123:test"] = new JArray(JToken.FromObject(new { ... } ));

which will create a single-element array containing your anonymously typed object.

fiddle

  • Related