创建时Json格式错误

时间:2014-11-10 11:14:51

标签: c# json windows-applications

我已经从列表中创建了一个json文件,截至目前代码工作正常。但是在代码中我需要检查文件是否存在同名,如果是这样,只需将新细节附加到文件中,否则创建一个新文件。不幸的是,文件的格式错误。 这是我的代码

 List<DeviceData> tempDate = new List<DeviceData>();
                                DeviceData D = new DeviceData();
                                D.deviceId = St_Id.ToString();
                                D.ansId = AnswerStr;

                                D.date = DateTime.Now;
                                tempDate.Add(D);
                                string ans = JsonConvert.SerializeObject(tempDate, Formatting.Indented);

                                //System.IO.File.WriteAllText(@"E:\" + " device.json", ans);

                                if (File.Exists(@"E:\" + " device.json"))
                                {
                                    File.AppendAllText(@"E:\" + " device.json", ans);
                                }
                                else
                                {
                                    System.IO.File.WriteAllText(@"E:\" + " device.json", ans);
                                }

我得到的文件是

[
  {
    "deviceId": "2",
    "ansId": "2",
    "date": "2014-11-10T15:30:58.7717853+05:30"
  }
][
  {
    "deviceId": "4",
    "ansId": "1",
    "date": "2014-11-10T15:31:00.8717853+05:30"
  }
]

enter image description here

任何人都可以提供帮助。谢谢提前

2 个答案:

答案 0 :(得分:1)

格式错误,应该是这样的:

[
    {
        "deviceId": "2",
        "ansId": "2",
        "date": "2014-11-10T15:30:58.7717853+05:30"
    },
    {
        "deviceId": "4",
        "ansId": "1",
        "date": "2014-11-10T15:31:00.8717853+05:30"
    }
]

所以你必须修改你的代码:

if (File.Exists(@"E:\" + " device.json"))
{
     ans = ans.Replace('[', ',');
     var json =  File.ReadAllText(@"E:\" + " device.json");
     json.Replace("]", ans);
     File.AppendAllText(@"E:\" + " device.json", json);
}

答案 1 :(得分:0)

问题似乎是你的json文件中有多个数组。

一个解决方案是首先将旧的json解析为新列表,然后添加新设备,然后用。覆盖该文件。

另一个是借助正则表达式从解码中提取内容,并将其插入旧的json文件中(在最后一个&#34;}&#34;和&#34;之间。 ]&#34;)