【发布时间】:2017-06-24 01:25:05
【问题描述】:
我正在尝试用 C# 编写一个 JSON 文件,但我遇到了一个问题,我想用逗号 (',') 分隔每个对象以使其成为有效的 JSON,但是我不知道如何去做这个。我已经搜索过是否有一种方法可以在字符串中搜索特定模式(在我的情况下是“}{”),并且正则表达式可能有效,但我不知道如何创建一个。
最终结果应该是这样的
'},{'
而不是
'}{'.
到目前为止,这是我的代码:
private void loopThroughArray()
{
string json = "";
for (int i = 0; i < array.Count; i++)
{
MyObject t = array[i];
json += new JavaScriptSerializer().Serialize(t);
//this writes the json to the file but without comma seperator
}
System.IO.File.WriteAllText(@"<MyFilepath>\json.txt", "{\"json\":[" + json + "]}");
//this writes the json to a file that and is in a json array called 'json'
}
【问题讨论】:
-
为什么要编写自己的 JSON 序列化程序?如果可以的话,应该使用newtonsoft.com/json 之类的东西。
-
我会看看 Newtonsoft 的,我知道它对反序列化有好处。我认为 JavaScriptSerializer 和我得到的一样好。