-1

我想从键值对映射 JSON 路径属性以在C#中生成 JSON 对象,其中路径包含嵌套数组索引路径

输入:

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");

输出:

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

使用Jackson 的 JavaPropsMapper可以轻松实现,如下所示:

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

如何在C#中实现这个想法,以便我能够从给定的 JSON 路径节点生成 JSON 对象。

4

1 回答 1

1

您可以创建匿名对象序列化

            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);
于 2020-12-10T11:20:13.860 回答