Reputation: 1482
I have created a json file from a list and as of now the code is working fine. But in the code I need to check whether a file exist with the same name, if so just append the new details to the file else create a new file. Unfortunately the file is getting written in a wrong format. Here is my code
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);
}
The file I getting is
[
{
"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"
}
]
Can any one help .Thanks in advance
Upvotes: 0
Views: 94
Reputation: 191
The format is wrong and it should be like this:
[
{
"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"
}
]
So you have to modify your code like this:
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);
}
Upvotes: 1
Reputation: 151
The Problem seems to be that you have multipley arrays in you json file.
One Solution would be to first Parse your old json to a new list, then add the new device und then overwrite the file with.
The other one would be to extract the content from the decoding with the help of a regular expression, and inserting it in the old json file (between the last "}" und the "]")
Upvotes: 0