Converting a string to JSON in C#

Trip picture Trip · Sep 27, 2016 · Viewed 58.9k times · Source

I'm trying to use Simple JSON to convert this string to JSON :

"{\"objects\":[{\"id\":1,\"title\":\"Book\",\"position_x\":0,\"position_y\":0,\"position_z\":0,\"rotation_x\":0,\"rotation_y\":0,\"rotation_z\":0,\"created\":\"2016-09-21T14:22:22.817Z\"},{\"id\":2,\"title\":\"Apple\",\"position_x\":0,\"position_y\":0,\"position_z\":0,\"rotation_x\":0,\"rotation_y\":0,\"rotation_z\":0,\"created\":\"2016-09-21T14:22:52.368Z\"}]}"

Unfortunately, it appears that Visual Studio doesn't have Interactive Debugging Console. As in, placing a debugger on a line, and stepping into that part of the code in a live interactive console. Where I would otherwise be able to experiment with SimpleJSON's library and see how to make this work. By all means, correct me if I'm wrong!

Being that that's impossible though, would anyone know how to accomplish this? I have tried this :

JSONData jsonData = new JSONData(my_json_string);

But that escapes the string even more and keeps it a string :

"\"{\\\"objects\\\":[{\\\"id\\\":1,\\\"title\\\":\\\"Book\\\",\\\"position_x\\\":0,\\\"position_y\\\":0,\\\"position_z\\\":0,\\\"rotation_x\\\":0,\\\"rotation_y\\\":0,\\\"rotation_z\\\":0,\\\"created\\\":\\\"2016-09-21T14:22:22.817Z\\\...

I'm new to C#, but I'm surprised there's nothing native to C# that would make something as common as parsing JSON more accessible. Is there one?

Answer

M. Wiśnicki picture M. Wiśnicki · Sep 27, 2016

First, create your data model. You can use json2sharp, very helpful tool.

public class Item
{
    public int id { get; set; }
    public string title { get; set; }
    public int position_x { get; set; }
    public int position_y { get; set; }
    public int position_z { get; set; }
    public int rotation_x { get; set; }
    public int rotation_y { get; set; }
    public int rotation_z { get; set; }
    public string created { get; set; }
}

Next use Newtonsoft.Json and call deserialize method.

var list = JsonConvert.DeserializeObject<List<Item>>(Yourjson);