Himanshu Dwivedi
Himanshu Dwivedi

Reputation: 8174

How to create JSON object from JSON node path in C#

I want to map JSON path properties from key-value pairs to generate the JSON object in C# where the path contains nested array index path

Input:

Dictionary<string, string> properties = new Dictionary<string, string>();
properties.put("id", "1");
properties.put("name", "sample_name");
properties.put("category.id", "1");
properties.put("category.name", "sample");
properties.put("tags[0].id", "1");
properties.put("tags[0].name", "tag1");
properties.put("tags[1].id", "2");
properties.put("tags[1].name", "tag2");
properties.put("status", "available");

Output:

{
  "id": 1,
  "name": "sample_name",
  "category": {
    "id": 1,
    "name": "sample"
  },
  "tags": [
    {
      "id": 1,
      "name": "tag1"
    },
    {
      "id": 2,
      "name": "tag2"
    }
  ],
 
  "status": "available"
}

Using Jackson's JavaPropsMapper it can easily be achieved like:

JavaPropsMapper javaPropsMapper = new JavaPropsMapper();
JsonNode json = javaPropsMapper.readMapAs(properties, JsonNode.class);

How to implement this idea in C# so that I am able to generate the JSON object from the given JSON path node.

Upvotes: 0

Views: 2288

Answers (1)

coder_b
coder_b

Reputation: 1025

you can create anonymous object an serialize

            var values = new { 
                id = "id",
                name = "name",
                category = new { id = 1, name = "sample"},
                tags = new { id = 0, name = "sample" },
                status = "available"
            }; 
            string json = JsonConvert.SerializeObject(values);

Upvotes: 1

Related Questions