0

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

1
  • are you appending the json result of the serialize call to the file every time you create and serilaize the object? I'm guessing so and that's your problem Commented Jun 27, 2016 at 22:35

3 Answers 3

3

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));
Sign up to request clarification or add additional context in comments.

Comments

1

[{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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.