Converting a string to JSON in C#
Asked Answered
V

3

19

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?

Visby answered 27/9, 2016 at 11:9 Comment(5)
That string is json. JSon isn't some magic object, it's a format in which a string can be, in which case you could call that string a json string. The reason it escapes even more is because it's trying to format the inputted string as json, so that when you deserialize you get the input again.Jayejaylene
"But that escapes the string even more and keeps it a string", not true, see this post. You can use the intermediate window to test your code while debugging.Tryout
Use Newtonsoft JSON to serialize and deserialize JSON. It is easy and well documented.Tryout
@Jayejaylene But I couldn't just do object[0] to a stringVisby
Exactly, because json isn't an object. If you want to convert that json string to an object then you need to deserialize that string, by for instance a library that does precisely that.Jayejaylene
P
18

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);
Pebbly answered 27/9, 2016 at 11:17 Comment(3)
Good note about json2csharp - it's a lifesaver and I've used it a lot. A useful, and lesser-known tool is also built into VS (those of you that use it). Copy the JSON to the clipboard, and then create/open a code file. Click Edit > Paste Special > Paste JSON As Classes. Does the same job, just straight in the IDE :) there's also an option of XML As ClassesKanishakanji
app.quicktype.io/#l=C%23 and jsonplaceholder.typicode.comInpatient
I cannot understand why C#'ers always advise creating the model? Isn't there anyway without a model?Decennium
S
23

The question asks how to convert a string to a JSON object... This can be achieved without using a Class or data model, as follows:

using Newtonsoft.Json;

string str = "{\"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\"}]}";
dynamic json = JsonConvert.DeserializeObject(str);

Now, you can access the json contents as follows:

json["objects"][0]["title"];

returns "Book"

One option for an "Interactive Debugging Console" where you can play around with C# code is Xamarin Workbooks... microsoft.com/en-us/xamarin/tools/workbooks/

Xamarin Workbooks provide a blend of documentation and code that is perfect for experimentation, learning, and creating... blah blah blah

Smelter answered 14/11, 2018 at 12:1 Comment(2)
any advantage of using dynamic over var?Openhearted
@ahong, they server different purpose. Var is used when u can determine type at compile time. dynamic is used then the type is dymanically determined/generated at run timeYahweh
P
18

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);
Pebbly answered 27/9, 2016 at 11:17 Comment(3)
Good note about json2csharp - it's a lifesaver and I've used it a lot. A useful, and lesser-known tool is also built into VS (those of you that use it). Copy the JSON to the clipboard, and then create/open a code file. Click Edit > Paste Special > Paste JSON As Classes. Does the same job, just straight in the IDE :) there's also an option of XML As ClassesKanishakanji
app.quicktype.io/#l=C%23 and jsonplaceholder.typicode.comInpatient
I cannot understand why C#'ers always advise creating the model? Isn't there anyway without a model?Decennium
C
0

Did you try system utilities?

Like this one https://msdn.microsoft.com/ru-ru/library/system.json.jsonvalue.parse%28v=vs.95%29.aspx

You can use

public static JsonValue Parse(string jsonString)

from JsonValue class and cast then to jsonobject or anything you want.

Chuipek answered 27/9, 2016 at 11:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.