Converting a string to JSON in C#

痞子三分冷 提交于 2019-12-04 03:32:50
M. Wiśnicki

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);

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

Amir Rasulov

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!