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

前端 未结 21 2785
粉色の甜心
粉色の甜心 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 06:58

    Json.NET does this...

    string json = @"{""key1"":""value1"",""key2"":""value2""}";
    
    var values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
    

    More examples: Serializing Collections with Json.NET

    0 讨论(0)
  • 2020-11-21 06:58

    System.Text.Json

    This can now be done using System.Text.Json which is built-in to .NET Core 3.0. It's now possible to deserialize JSON without using third-party libraries.

    var json = @"{""key1"":""value1"",""key2"":""value2""}";
    var values = JsonSerializer.Deserialize<Dictionary<string, string>>(json);
    

    Also available in NuGet package System.Text.Json if using .NET Standard or .NET Framework.

    0 讨论(0)
  • 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.

    /// <summary>
    /// Deserialize the given JSON string data (<paramref name="data"/>) into a
    ///   dictionary.
    /// </summary>
    /// <param name="data">JSON string.</param>
    /// <returns>Deserialized dictionary.</returns>
    private IDictionary<string, object> DeserializeData(string data)
    {
        var values = JsonConvert.DeserializeObject<Dictionary<string, object>>(data);
    
        return DeserializeData(values);
    }
    
    /// <summary>
    /// Deserialize the given JSON object (<paramref name="data"/>) into a dictionary.
    /// </summary>
    /// <param name="data">JSON object.</param>
    /// <returns>Deserialized dictionary.</returns>
    private IDictionary<string, object> DeserializeData(JObject data)
    {
        var dict = data.ToObject<Dictionary<String, Object>>();
    
        return DeserializeData(dict);
    }
    
    /// <summary>
    /// Deserialize any elements of the given data dictionary (<paramref name="data"/>) 
    ///   that are JSON object or JSON arrays into dictionaries or lists respectively.
    /// </summary>
    /// <param name="data">Data dictionary.</param>
    /// <returns>Deserialized dictionary.</returns>
    private IDictionary<string, object> DeserializeData(IDictionary<string, object> 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;
    }
    
    /// <summary>
    /// Deserialize the given JSON array (<paramref name="data"/>) into a list.
    /// </summary>
    /// <param name="data">Data dictionary.</param>
    /// <returns>Deserialized list.</returns>
    private IList<Object> DeserializeData(JArray data)
    {
        var list = data.ToObject<List<Object>>();
    
        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;
    }
    
    0 讨论(0)
  • 2020-11-21 06:59

    I did discover .NET has a built in way to cast the JSON string into a Dictionary<String, Object> via the System.Web.Script.Serialization.JavaScriptSerializer type in the 3.5 System.Web.Extensions assembly. Use the method DeserializeObject(String).

    I stumbled upon this when doing an ajax post (via jquery) of content type 'application/json' to a static .net Page Method and saw that the method (which had a single parameter of type Object) magically received this Dictionary.

    0 讨论(0)
  • 2020-11-21 07:00

    A bit late to the game, but non of the above solutions pointed me in the direction of a pure and simple .NET, no json.net solution. So here it is, ended up being very simple. Below a full running example of how it is done with standard .NET Json serialization, the example has dictionary both in the root object and in the child objects.

    The golden bullet is this cat, parse the settings as second parameter to the serializer:

    DataContractJsonSerializerSettings settings =
                           new DataContractJsonSerializerSettings();
                        settings.UseSimpleDictionaryFormat = true;
    

    Full code below:

    using System;
    using System.Collections.Generic;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Json;
    
        namespace Kipon.dk
        {
            public class JsonTest
            {
                public const string EXAMPLE = @"{
                    ""id"": ""some id"",
                    ""children"": {
                    ""f1"": {
                        ""name"": ""name 1"",
                        ""subs"": {
                        ""1"": { ""name"": ""first sub"" },
                        ""2"": { ""name"": ""second sub"" }
                        }
                    },
                    ""f2"": {
                        ""name"": ""name 2"",
                        ""subs"": {
                        ""37"": { ""name"":  ""is 37 in key""}
                        }
                    }
                    }
                }
                ";
    
                [DataContract]
                public class Root
                {
                    [DataMember(Name ="id")]
                    public string Id { get; set; }
    
                    [DataMember(Name = "children")]
                    public Dictionary<string,Child> Children { get; set; }
                }
    
                [DataContract]
                public class Child
                {
                    [DataMember(Name = "name")]
                    public string Name { get; set; }
    
                    [DataMember(Name = "subs")]
                    public Dictionary<int, Sub> Subs { get; set; }
                }
    
                [DataContract]
                public class Sub
                {
                    [DataMember(Name = "name")]
                    public string Name { get; set; }
                }
    
                public static void Test()
                {
                    var array = System.Text.Encoding.UTF8.GetBytes(EXAMPLE);
                    using (var mem = new System.IO.MemoryStream(array))
                    {
                        mem.Seek(0, System.IO.SeekOrigin.Begin);
                        DataContractJsonSerializerSettings settings =
                           new DataContractJsonSerializerSettings();
                        settings.UseSimpleDictionaryFormat = true;
    
                        var ser = new DataContractJsonSerializer(typeof(Root), settings);
                        var data = (Root)ser.ReadObject(mem);
                        Console.WriteLine(data.Id);
                        foreach (var childKey in data.Children.Keys)
                        {
                            var child = data.Children[childKey];
                            Console.WriteLine(" Child: " + childKey + " " + child.Name);
                            foreach (var subKey in child.Subs.Keys)
                            {
                                var sub = child.Subs[subKey];
                                Console.WriteLine("   Sub: " + subKey + " " + sub.Name);
                            }
                        }
                    }
                }
            }
        }
    
    0 讨论(0)
  • 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<string> allDrives = o["Drives"].Select(t => (string)t).ToList();
    // DVD read/writer
    // 500 gigabyte hard drive
    
    0 讨论(0)
提交回复
热议问题