我有一个 Windows Forms .Net 应用程序,我正在使用 Newtonsoft Json.Net 库将 Json 格式的文本写入文本文件。我想写两组括号来表示 points 是一个列表列表,即使它只包含一个列表(如下所示)。
{
"rallyPoints:" {
"points": [
[
0.0,
1.0,
2.0
]
]
}
}
这是我的代码
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.IO;
void exampleFunction()
{
string filePath = @"path/to/file.json";
List<List<double>> rallyPoints = new List<List<double>>();
List<double> singleRallyPoint = new List<double>
{
0.0, 1.0, 2.0
};
rallyPoints.Add(singleRallyPoint);
JObject mainObject = new JObject(
new JProperty("rallyPoints", new JObject(
new JProperty("points", rallyPoints)
))
);
using (StreamWriter file = File.CreateText(filePath))
using (JsonTextWriter writer = new JsonTextWriter(file))
{
writer.Formatting = Formatting.Indented;
mainObject.WriteTo(writer);
}
}
我的代码写入文本文件,如下所示。请注意,points 只有一组括号而不是两组,因此不清楚这是一个列表列表。
{
"rallyPoints:" {
"points": [
0.0,
1.0,
2.0
]
}
}
我不确定我想要完成的是不是正确的 Json 格式。也许是这样的情况,使用 Json 的列表列表仅包含一个列表作为元素被格式化为列表。到目前为止,我还无法在线验证这一点。即使我尝试的不是正确的 Json,我仍然想知道是否有解决方案。谢谢。
将
List<List<double>>
转换为 JArray
应该可以解决问题。
JArray.FromObject(rallyPoints)
JObject mainObject = new JObject(
new JProperty("rallyPoints",
new JObject(
new JProperty("points", JArray.FromObject(rallyPoints))
)
)
);
最简单的方法是使用匿名类型
void exampleFunction()
{
string filePath = @"path/to/file.json";
var result = new
{
rallyPoinst = new
{
points = new List<List<double>> {
new List<double> {
0.0, 1.0, 2.0
}}
}
};
var json=JsonConvert.SerializeObject(result, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText(filePath, json);
}