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

前端 未结 21 2803
粉色の甜心
粉色の甜心 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:08

    I just needed to parse a nested dictionary, like

    {
        "x": {
            "a": 1,
            "b": 2,
            "c": 3
        }
    }
    

    where JsonConvert.DeserializeObject doesn't help. I found the following approach:

    var dict = JObject.Parse(json).SelectToken("x").ToObject>();
    

    The SelectToken lets you dig down to the desired field. You can even specify a path like "x.y.z" to step further down into the JSON object.

提交回复
热议问题