我有以下一组变量JSON数据,其中第一行是元素名称列表,其他行表示元素值列表:
sliceA = reshape(vectorA, 128, []); % correct number of slices of 128
sliceA = reshape(vectorA, [], N); % This would use N how you are in the loop
我想从数据构建以下类型的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对象。我没有看到任何直接支持使用JSON.NET API执行此操作。 非常感谢任何帮助。
答案 0 :(得分:0)
这只是让你走上正确轨道的想法。
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"
}
]
}
希望这有帮助。
答案 1 :(得分:0)
您可以使用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();