简体   繁体   中英

Proper way to initialize a C# dictionary with JavaScript json file?

I currently have a Web Socket between JavaScript and a server programmed in ASP.Net MVC 5. Does anyone know if there is a way I can insert json file into a C# dictionary when I create it? In JavaScript, I can pass data easily, but How can I initialize C# dictionary with json format like this?

  {"id": "svgContent","children": [
     {"id": "circle1","tag": "path",
     "value": "M0,160A160,160 0 1,1 0,-160A160,160 0 1,1 0,160M0,100A100,100 0 1,0 0,-100A100,100 0 1,0 0,100Z",
"children": [
    { "id": "point", "cx": "-67.59530401363443", "cy": "-93.03695435311894" },
    { "id": "point", "cx": "-109.37149937394265", "cy": "35.53695435311897" },
    { "id": "point", "cx": "1.4083438190194563e-14", "cy": "115" }
  ]

 },
       {"id": "circle2","tag": "path","value": "M0,260A260,260 0 1,1 0,-260A260,260 0 1,1 0,260M0,200A200,200 0 1,0 0,-200A200,200 0 1,0 0,200Z",
"children": [                
    { "id": "point", "cx": "-126.37382924288177", "cy": "-173.93865379061367" },
    { "id": "point", "cx": "-204.477151003458", "cy": "66.43865379061373" },
    { "id": "point", "cx": "2.6329906181668095e-14", "cy": "215" }

    ]

  }

]}

You should create a matching class to suit this JSON data model, and than Deserialize the data into the C# object.

  1. You should add the framework Json.NET
  2. Create C# Data model
  3. Deserialize the data from JSON to C# model.

Example of DataModel:

public class Child2
{
    public string id { get; set; }
    public string cx { get; set; }
    public string cy { get; set; }
}

public class Child
{
    public string id { get; set; }
    public string tag { get; set; }
    public string value { get; set; }
    public List<Child2> children { get; set; }
}

public class RootObject
{
    public string id { get; set; }
    public List<Child> children { get; set; }
}

Example of Deserilize:

var createdObject = JsonConvert.DeserializeObject<RootObject>(jsonText);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM