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

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

    I just implemented this in RestSharp. This post was helpful to me.

    Besides the code in the link, here is my code. I now get a Dictionary of results when I do something like this:

    var jsonClient = new RestClient(url.Host);
    jsonClient.AddHandler("application/json", new DynamicJsonDeserializer());
    var jsonRequest = new RestRequest(url.Query, Method.GET);
    Dictionary<string, dynamic> response = jsonClient.Execute<JObject>(jsonRequest).Data.ToObject<Dictionary<string, dynamic>>();
    

    Be mindful of the sort of JSON you're expecting - in my case, I was retrieving a single object with several properties. In the attached link, the author was retrieving a list.

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

    Tried to not use any external JSON implementation so i deserialised like this:

    string json = "{\"id\":\"13\", \"value\": true}";
    
    var serializer = new JavaScriptSerializer(); //using System.Web.Script.Serialization;
    
    Dictionary<string, string> values = serializer.Deserialize<Dictionary<string, string>>(json);
    
    0 讨论(0)
  • 2020-11-21 07:25

    My approach directly deserializes to IDictionary, without JObject or ExpandObject in between. The code uses converter, which is basically copied from ExpandoObjectConverter class found in JSON.NET sourcecode, but using IDictionary instead of ExpandoObject.

    Usage:

    var settings = new JsonSerializerSettings()
    {
        Converters = { new DictionaryConverter() },
    };
    var result = JsonConvert.DeserializeObject<IDictionary<string, object>>(json, settings);
    

    Code:

    // based on ExpandoObjectConverter, but using arrays instead of IList, to behave similar to System.Web.Script.Serialization.JavaScriptSerializer
    public class DictionaryConverter : JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            return ReadValue(reader);
        }
    
        public override bool CanConvert(Type objectType)
        {
            return (objectType == typeof(IDictionary<string, object>));
        }
    
        public override bool CanWrite
        {
            get { return false; }
        }
    
        private object ReadValue(JsonReader reader)
        {
            while (reader.TokenType == JsonToken.Comment)
            {
                if (!reader.Read())
                    throw JsonSerializationExceptionCreate(reader, "Unexpected end when reading IDictionary<string, object>.");
            }
    
            switch (reader.TokenType)
            {
                case JsonToken.StartObject:
                    return ReadObject(reader);
                case JsonToken.StartArray:
                    return ReadList(reader);
                default:
                    if (IsPrimitiveToken(reader.TokenType))
                        return reader.Value;
    
                    throw JsonSerializationExceptionCreate(reader, string.Format(CultureInfo.InvariantCulture, "Unexpected token when converting IDictionary<string, object>: {0}", reader.TokenType));
            }
        }
    
        private object ReadList(JsonReader reader)
        {
            List<object> list = new List<object>();
    
            while (reader.Read())
            {
                switch (reader.TokenType)
                {
                    case JsonToken.Comment:
                        break;
                    default:
                        object v = ReadValue(reader);
    
                        list.Add(v);
                        break;
                    case JsonToken.EndArray:
                        return list;
                }
            }
    
            throw JsonSerializationExceptionCreate(reader, "Unexpected end when reading IDictionary<string, object>.");
        }
    
        private object ReadObject(JsonReader reader)
        {
            IDictionary<string, object> dictionary = new Dictionary<string, object>();
            while (reader.Read())
            {
                switch (reader.TokenType)
                {
                    case JsonToken.PropertyName:
                        string propertyName = reader.Value.ToString();
    
                        if (!reader.Read())
                            throw JsonSerializationExceptionCreate(reader, "Unexpected end when reading IDictionary<string, object>.");
    
                        object v = ReadValue(reader);
    
                        dictionary[propertyName] = v;
                        break;
                    case JsonToken.Comment:
                        break;
                    case JsonToken.EndObject:
                        return dictionary;
                }
            }
    
            throw JsonSerializationExceptionCreate(reader, "Unexpected end when reading IDictionary<string, object>.");
        }
    
        //based on internal Newtonsoft.Json.JsonReader.IsPrimitiveToken
        internal static bool IsPrimitiveToken(JsonToken token)
        {
            switch (token)
            {
                case JsonToken.Integer:
                case JsonToken.Float:
                case JsonToken.String:
                case JsonToken.Boolean:
                case JsonToken.Undefined:
                case JsonToken.Null:
                case JsonToken.Date:
                case JsonToken.Bytes:
                    return true;
                default:
                    return false;
            }
        }
    
        // based on internal Newtonsoft.Json.JsonSerializationException.Create
        private static JsonSerializationException JsonSerializationExceptionCreate(JsonReader reader, string message, Exception ex = null)
        {
            return JsonSerializationExceptionCreate(reader as IJsonLineInfo, reader.Path, message, ex);
        }
    
        // based on internal Newtonsoft.Json.JsonSerializationException.Create
        private static JsonSerializationException JsonSerializationExceptionCreate(IJsonLineInfo lineInfo, string path, string message, Exception ex)
        {
            message = JsonPositionFormatMessage(lineInfo, path, message);
    
            return new JsonSerializationException(message, ex);
        }
    
        // based on internal Newtonsoft.Json.JsonPosition.FormatMessage
        internal static string JsonPositionFormatMessage(IJsonLineInfo lineInfo, string path, string message)
        {
            if (!message.EndsWith(Environment.NewLine))
            {
                message = message.Trim();
    
                if (!message.EndsWith(".", StringComparison.Ordinal))
                    message += ".";
    
                message += " ";
            }
    
            message += string.Format(CultureInfo.InvariantCulture, "Path '{0}'", path);
    
            if (lineInfo != null && lineInfo.HasLineInfo())
                message += string.Format(CultureInfo.InvariantCulture, ", line {0}, position {1}", lineInfo.LineNumber, lineInfo.LinePosition);
    
            message += ".";
    
            return message;
        }
    }
    
    0 讨论(0)
提交回复
热议问题