0

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.

3
  • Which JSON serialiser are you using? Commented Dec 10, 2020 at 11:19
  • I am using Newtonsoft JSON serializer Commented Dec 10, 2020 at 11:20
  • Similar question here: Update JSON object using path and value Commented Dec 11, 2020 at 6:44

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

First of all how would I parse the given expression in my dictionary such as tags[0].id. I have this input dynamic in nature. I can get any kind of expression out of which I need to generate the JSON node

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.