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

前端 未结 21 3171
粉色の甜心
粉色の甜心 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条回答
  •  旧时难觅i
    2020-11-21 06:58

    I've added upon the code submitted by jSnake04 and Dasun herein. I've added code to create lists of objects from JArray instances. It has two-way recursion but as it is functioning on a fixed, finite tree model, there is no risk of stack overflow unless the data is massive.

    /// 
    /// Deserialize the given JSON string data () into a
    ///   dictionary.
    /// 
    /// JSON string.
    /// Deserialized dictionary.
    private IDictionary DeserializeData(string data)
    {
        var values = JsonConvert.DeserializeObject>(data);
    
        return DeserializeData(values);
    }
    
    /// 
    /// Deserialize the given JSON object () into a dictionary.
    /// 
    /// JSON object.
    /// Deserialized dictionary.
    private IDictionary DeserializeData(JObject data)
    {
        var dict = data.ToObject>();
    
        return DeserializeData(dict);
    }
    
    /// 
    /// Deserialize any elements of the given data dictionary () 
    ///   that are JSON object or JSON arrays into dictionaries or lists respectively.
    /// 
    /// Data dictionary.
    /// Deserialized dictionary.
    private IDictionary DeserializeData(IDictionary data)
    {
        foreach (var key in data.Keys.ToArray()) 
        {
            var value = data[key];
    
            if (value is JObject)
                data[key] = DeserializeData(value as JObject);
    
            if (value is JArray)
                data[key] = DeserializeData(value as JArray);
        }
    
        return data;
    }
    
    /// 
    /// Deserialize the given JSON array () into a list.
    /// 
    /// Data dictionary.
    /// Deserialized list.
    private IList DeserializeData(JArray data)
    {
        var list = data.ToObject>();
    
        for (int i = 0; i < list.Count; i++)
        {
            var value = list[i];
    
            if (value is JObject)
                list[i] = DeserializeData(value as JObject);
    
            if (value is JArray)
                list[i] = DeserializeData(value as JArray);
        }
    
        return list;
    }
    
        

    提交回复
    热议问题