TwoTen TwoTen - 1 month ago 16
JSON Question

Custom Object List To JSON And Back To Custom Object List C#

I have a custom object that looks like this:

public class myObject
{
public string address;
public int port;
}


I have a list of "myObject". I then want to make the list of myObjects and convert it to JSON formating with JSON.net. I then Want to be able to Convert it back into a List of myObject. Simply using SerializeObject and DeserializeObject doesn't seem to do the trick.
Happy for help.

Answer

Pretty simple, using JSON.NET ( http://www.newtonsoft.com/ )

void Main()
{
    var list = new List<myObject>() { new myObject() {address="address", port=11}};

    string json = JsonConvert.SerializeObject(list);

    var deserialized = JsonConvert.DeserializeObject<List<myObject>>(json);
}

public class myObject
{
    public string address;
    public int port;
}
Comments