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

前端 未结 21 3289
粉色の甜心
粉色の甜心 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 Data { get; set; }
    }
    

    Then use it like this:

    var serializer = new DataContractJsonSerializer(typeof(List));
    var jsonParams = @"{""data"": [{""Key"":""foo"",""Value"":""bar""}] }";
    var stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonParams));
    
    var obj = serializer.ReadObject(stream);
    Console.WriteLine(obj);
    

提交回复
热议问题