How can I deserialize JSON to a simple Dictionary in ASP.NET?

前端 未结 21 3139
粉色の甜心
粉色の甜心 2020-11-21 06:33

I have a simple key/value list in JSON being sent back to ASP.NET via POST. Example:

{ \"key1\": \"value1\", \"key2\": \"value2\"}

21条回答
  •  遥遥无期
    2020-11-21 07:01

    For anyone who is trying to convert JSON to dictionary just for retrieving some value out of it. There is a simple way using Newtonsoft.JSON

    using Newtonsoft.Json.Linq
    ...
    
    JObject o = JObject.Parse(@"{
      'CPU': 'Intel',
      'Drives': [
        'DVD read/writer',
        '500 gigabyte hard drive'
      ]
    }");
    
    string cpu = (string)o["CPU"];
    // Intel
    
    string firstDrive = (string)o["Drives"][0];
    // DVD read/writer
    
    IList allDrives = o["Drives"].Select(t => (string)t).ToList();
    // DVD read/writer
    // 500 gigabyte hard drive
    

提交回复
热议问题