【问题标题】:How to create JSON object from JSON node path in C#如何在 C# 中从 JSON 节点路径创建 JSON 对象
【发布时间】:2021-03-21 18:41:21
【问题描述】:

我想从键值对映射 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's JavaPropsMapper 可以轻松实现:

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

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

【问题讨论】:

标签: c# arrays json json.net json-path-expression


【解决方案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);

【讨论】:

  • 首先,我将如何解析我的字典中的给定表达式,例如 tags[0].id。我本质上具有这种输入动态。我可以得到任何需要生成 JSON 节点的表达式
猜你喜欢
  • 1970-01-01
  • 2017-11-06
  • 2018-04-30
  • 2021-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-04
相关资源
最近更新 更多