变换嵌套的JSON数组到JSON对象的数组中



i具有以下一组变量JSON数据,其中第一行是元素名称列表,而其他行表示元素值列表:

[
  [
    "category",
    "author",
    "title",
    "price"
  ],
  [
    "reference",
    "Nigel Rees",
    "Sayings of the Century",
    "8.95"
  ],
  [
    "fiction",
    "Evelyn Waugh",
    "Sword of Honour",
    "12.99"
  ],
  [
    "fiction",
    "Herman Melville",
    "Moby Dick",
    "8.99"
  ],
  [
    "fiction",
    "J. R. R. Tolkien",
    "The Lord of the Rings",
    "22.99"
  ]
]

我想从数据构建以下类型的JSON对象:

{
  "book": [
    {
      "category": "reference",
      "author": "Nigel Rees",
      "title": "Sayings of the Century",
      "price": 8.95
    },
    {
      "category": "fiction",
      "author": "Evelyn Waugh",
      "title": "Sword of Honour",
      "price": 12.99
    },
    {
      "category": "fiction",
      "author": "Herman Melville",
      "title": "Moby Dick",
      "isbn": "0-553-21311-3",
      "price": 8.99
    },
    {
      "category": "fiction",
      "author": "J. R. R. Tolkien",
      "title": "The Lord of the Rings",
      "isbn": "0-395-19395-8",
      "price": 22.99
    }
  ]
}

如何构建我的JSON对象,该对象应与上述相同。我没有看到使用JSON.NET API进行此操作的任何直接支持。任何帮助都非常感谢。

这只是让您进入正确轨道的想法。

        JObject obj = new JObject();
        var child = new JArray();
        var child2 = new JObject();
        child2.Add("category", "references");
        child.Add(child2);
        obj.Add("book", child);
        var result = obj.ToString();

我不会为您进行琴弦解析,我认为您应该能够处理。

我给出的代码会产生以下JSON:

               {
                "book": [
                  {
                      "category": "references"
                    }
                  ]
                }

希望这会有所帮助。

您可以使用json.net的linq-to-json api进行此转换:

JArray array = JArray.Parse(origJson);
string[] keys = array.First().Select(t => t.ToString()).ToArray();
JArray array2 = 
    new JArray(array.Skip(1).Select(a => 
        new JObject(a.Select((t, i) => 
            new JProperty(keys[i], t)
        ))
    ));
JObject obj = new JObject(new JProperty("book", array2));
string finalJson = obj.ToString();

小提琴:https://dotnetfiddle.net/kmyhoe

相关内容

  • 没有找到相关文章

最新更新