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

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

    I added a check for null values in the JSON to the other answer

    I had same problem so I wrote this my self. This solution is differentiated from other answers because it can deserialize in to multiple levels.

    Just send json string in to deserializeToDictionary function it will return non strongly-typed Dictionary object.

    private Dictionary deserializeToDictionary(string jo)
    {
        var values = JsonConvert.DeserializeObject>(jo);
        var values2 = new Dictionary();
        foreach (KeyValuePair d in values)
        {
            if (d.Value != null && d.Value.GetType().FullName.Contains("Newtonsoft.Json.Linq.JObject"))
            {
                values2.Add(d.Key, deserializeToDictionary(d.Value.ToString()));
            }
            else
            {
                values2.Add(d.Key, d.Value);
            }
        }
        return values2;
    }
    

    Ex: This will return Dictionary object of a Facebook JSON response.

    private void button1_Click(object sender, EventArgs e)
    {
        string responsestring = "{\"id\":\"721055828\",\"name\":\"Dasun Sameera
            Weerasinghe\",\"first_name\":\"Dasun\",\"middle_name\":\"Sameera\",\"last_name\":\"Weerasinghe\",\"username\":\"dasun\",\"gender\":\"male\",\"locale\":\"en_US\",
            hometown: {id: \"108388329191258\", name: \"Moratuwa, Sri Lanka\",}}";
        Dictionary values = deserializeToDictionary(responsestring);
    }
    

    Note: hometown further deserialize into a Dictionary object.

提交回复
热议问题