Reputation: 75
I'm having troubles making JSON file from my Server
class. This is my class:
public class CsServerInfo
{
public string ip { get; set; }
public string name { get; set; }
}
The idea is to add new servers into JSON file on a Button Click
. It means every time I click on a button (in a WPF window which has TextBoxes
for IP
and Name
properties) a new server should be added into JSON file.
CsServerInfo newServ = new CsServerInfo();
newServ.ip = this.serverIP.Text;
newServ.name = this.serverName.Text;
string json = JsonConvert.SerializeObject(newServ);
System.IO.File.AppendAllText(@"C:\JSON4.json", json);
The problem is I get JSON file that is not correctly formatted:
{"ip":"52.45.24.2","name":"new"}{"ip":"45.45.45.4","name":"new2"}
There's no comma between the servers and if I use ToArray()
I get:
[{"ip":"52.45.24.2","name":"new"}][{"ip":"45.45.45.4","name":"new2"}]
Correct format should be [{server properties}, {another server}]
but I'm not able to get that. Thanks for your help
Upvotes: 0
Views: 141
Reputation: 5764
[{server properties}, {another server}]
this is a list of objects.
You should serializie list
List<CsServerInfo> listServ = new List<CsServerInfo>;
...
string json = JsonConvert.SerializeObject(listServ );
If you need append in file you should read all from file to list, add new and save back.
Upvotes: 1
Reputation: 29207
Don't try to append JSON to the file. Let Json.NET handle the work of serializing to JSON. You should be manipulating a List<CsServerInfo>
and serializing the entire list when you're done modifying it. That way when you serialize and save, Json.NET is generating the JSON, which it does well, and it will be correctly formatted.
Upvotes: 0
Reputation: 56536
You're appending the JSON text of one server at a time to the file. You should parse the existing list, add your server, and then serialize the whole list.
// TODO first check if there's an existing file or not
var servers =
JsonConvert.DeserializeObject<List<CsServerInfo>>(File.ReadAllText(@"C:\JSON4.json"));
servers.Add(newServ);
File.WriteAllText(@"C:\JSON4.json", JsonConvert.SerializeObject(servers));
Upvotes: 3