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

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

    I would suggest using System.Runtime.Serialization.Json that is part of .NET 4.5.

    [DataContract]
    public class Foo
    {
       [DataMember(Name = "data")]
       public Dictionary<string,string> Data { get; set; }
    }
    

    Then use it like this:

    var serializer = new DataContractJsonSerializer(typeof(List<Foo>));
    var jsonParams = @"{""data"": [{""Key"":""foo"",""Value"":""bar""}] }";
    var stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonParams));
    
    var obj = serializer.ReadObject(stream);
    Console.WriteLine(obj);
    
    0 讨论(0)
  • 2020-11-21 07:03

    Based on comments above try JsonConvert.DeserializeObject<Dictionary<string,dynamic>>(json)

    var json = @"{""key1"":1,""key2"":""value2"", ""object1"":{""property1"":""value1"",""property2"":[2,3,4,5,6,7]}}";
    var parsedObject = JsonConvert.DeserializeObject<Dictionary<string,dynamic>>(json);
    

    seems to work even for complex objects and lists.

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

    You could use Tiny-JSON

    string json = "{\"key1\":\"value1\", \"key2\":\"value2\"}";
    IDictionary<string, string> dict = Tiny.Json.Decode<Dictionary<string, string>>(json);
    
    0 讨论(0)
  • 2020-11-21 07:06

    It seems all of these answers here just assume you can get that little string out of a bigger object... for people looking to simply deserealize a large object with such a dictionary somewhere inside the mapping, and who are using the System.Runtime.Serialization.Json DataContract system, here's a solution:

    An answer on gis.stackexchange.com had this interesting link. I had to recover it with archive.org, but it offers a pretty much perfect solution: a custom IDataContractSurrogate class in which you implement exactly your own types. I was able to expand it easily.

    I made a bunch of changes in it, though. Since the original source is no longer available, I'll post the entire class here:

    using System;
    using System.CodeDom;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Json;
    using System.Text;
    
    namespace JsonTools
    {
        /// <summary>
        /// Allows using Dictionary&lt;String,String&gt; and Dictionary&lt;String,Boolean&gt; types, and any others you'd like to add.
        /// Source: https://web.archive.org/web/20100317222656/my6solutions.com/post/2009/06/30/DataContractSerializer-DataContractJsonSerializer-JavaScriptSerializer-XmlSerializer-for-serialization.aspx
        /// </summary>
        public class JsonSurrogate : IDataContractSurrogate
        {
            /// <summary>
            /// Deserialize an object with added support for the types defined in this class.
            /// </summary>
            /// <typeparam name="T">Contract class</typeparam>
            /// <param name="json">JSON String</param>
            /// <param name="encoding">Text encoding</param>
            /// <returns>The deserialized object of type T</returns>
            public static T Deserialize<T>(String json, Encoding encoding)
            {
                if (encoding == null)
                    encoding = new UTF8Encoding(false);
                DataContractJsonSerializer deserializer = new DataContractJsonSerializer(
                    typeof(T), new Type[0], int.MaxValue, true, new JsonSurrogate(), false);
                using (MemoryStream stream = new MemoryStream(encoding.GetBytes(json)))
                {
                    T result = (T)deserializer.ReadObject(stream);
                    return result;
                }
            }
    
            // make sure all values in this are classes implementing JsonSurrogateObject.
            private static Dictionary<Type, Type> KnownTypes = 
                new Dictionary<Type, Type>()
                {
                    {typeof(Dictionary<String, String>), typeof(SSDictionary)},
                    {typeof(Dictionary<String, Boolean>), typeof(SBDictionary)}
                };
    
            #region Implemented surrogate dictionary classes
    
            [Serializable]
            public class SSDictionary : SurrogateDictionary<String>
            {
                public SSDictionary() : base() {}
                protected SSDictionary (SerializationInfo info, StreamingContext context) : base(info, context) {}
            }
            [Serializable]
            public class SBDictionary : SurrogateDictionary<Boolean>
            {
                public SBDictionary() : base() {}
                protected SBDictionary (SerializationInfo info, StreamingContext context) : base(info, context) {}
            }
    
            #endregion
    
            /// <summary>Small interface to easily extract the final value from the object.</summary>
            public interface JsonSurrogateObject
            {
                Object DeserializedObject { get; }
            }
    
            /// <summary>
            /// Class for deserializing any simple dictionary types with a string as key.
            /// </summary>
            /// <typeparam name="T">Any simple type that will be deserialized correctly.</typeparam>
                [Serializable]
            public abstract class SurrogateDictionary<T> : ISerializable, JsonSurrogateObject
            {
                public Object DeserializedObject { get { return dict; } }
                private Dictionary<String, T> dict;
    
                public SurrogateDictionary()
                {
                    dict = new Dictionary<String, T>();
                }
    
                // deserialize
                protected SurrogateDictionary(SerializationInfo info, StreamingContext context)
                {
                    dict = new Dictionary<String, T>();
                    foreach (SerializationEntry entry in info)
                    {
                        // This cast will only work for base types, of course.
                        dict.Add(entry.Name, (T)entry.Value);
                    }
                }
                // serialize
                public void GetObjectData(SerializationInfo info, StreamingContext context)
                {
                    foreach (String key in dict.Keys)
                    {
                        info.AddValue(key, dict[key]);
                    }
                }
    
            }
    
            /// <summary>
                /// Uses the KnownTypes dictionary to get the surrogate classes.
            /// </summary>
            /// <param name="type"></param>
            /// <returns></returns>
            public Type GetDataContractType(Type type)
            {
                Type returnType;
                if (KnownTypes.TryGetValue(type, out returnType))
                {
                    return returnType;
                }
                return type;
            }
    
            public object GetObjectToSerialize(object obj, Type targetType)
            {
                throw new NotImplementedException();
            }
    
            /// <summary>
            ///     Gets the object out of the surrogate datacontract object. This function is the reason all surrogate objects need to implement the JsonSurrogateObject class.
            /// </summary>
            /// <param name="obj">Result of the deserialization</param>
            /// <param name="targetType">Expected target type of the deserialization</param>
            /// <returns></returns>
            public object GetDeserializedObject(object obj, Type targetType)
            {
                if (obj is JsonSurrogateObject)
                {
                    return ((JsonSurrogateObject)obj).DeserializedObject;
                }
                return obj;
            }
    
            public Type GetReferencedTypeOnImport(string typeName, string typeNamespace, object customData)
            {
                return null;
            }
    
            #region not implemented
    
            public object GetCustomDataToExport(MemberInfo memberInfo, Type dataContractType)
            {
                throw new NotImplementedException();
            }
    
            public object GetCustomDataToExport(Type clrType, Type dataContractType)
            {
                throw new NotImplementedException();
            }
    
            public void GetKnownCustomDataTypes(Collection<Type> customDataTypes)
            {
                throw new NotImplementedException();
            }
    
            public CodeTypeDeclaration ProcessImportedType(CodeTypeDeclaration typeDeclaration, CodeCompileUnit compileUnit)
            {
                throw new NotImplementedException();
            }
    
            #endregion
        }
    }
    

    To add new supported types to the class, you just need to add your class, give it the right constructors and functions (look at SurrogateDictionary for an example), make sure it inherits JsonSurrogateObject, and add its type mapping to the KnownTypes dictionary. The included SurrogateDictionary can serve as basis for any Dictionary<String,T> types where T is any type that does deserialize correctly.

    Calling it is really simple:

    MyObjtype newObj = JsonSurrogate.Deserialize<MyObjtype>(jsonStr, encoding);
    

    Note that for some reason this thing has trouble using key strings which contain spaces; they were simply not present in the final list. Might just be it's simply against json specs and the api I was calling was poorly implemented, mind you; I dunno. Anyway, I solved this by regex-replacing them with underscores in the raw json data and fixing the dictionary after the deserialization.

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

    For those searching the internet and stumbling upon this post, I wrote a blog post on how to use the JavaScriptSerializer class.

    Read more... http://procbits.com/2011/04/21/quick-json-serializationdeserialization-in-c/

    Here is an example:

    var json = "{\"id\":\"13\", \"value\": true}";
    var jss = new JavaScriptSerializer();
    var table = jss.Deserialize<dynamic>(json);
    Console.WriteLine(table["id"]);
    Console.WriteLine(table["value"]);
    
    0 讨论(0)
  • 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<Dictionary<string, int>>();
    

    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.

    0 讨论(0)
提交回复
热议问题