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

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

    Edit: This works, but the accepted answer using Json.NET is much more straightforward. Leaving this one in case someone needs BCL-only code.

    It’s not supported by the .NET framework out of the box. A glaring oversight – not everyone needs to deserialize into objects with named properties. So I ended up rolling my own:

     Public Class StringStringDictionary
        Implements ISerializable
        Public dict As System.Collections.Generic.Dictionary(Of String, String)
        Public Sub New()
            dict = New System.Collections.Generic.Dictionary(Of String, String)
        End Sub
        Protected Sub New(info As SerializationInfo, _
              context As StreamingContext)
            dict = New System.Collections.Generic.Dictionary(Of String, String)
            For Each entry As SerializationEntry In info
                dict.Add(entry.Name, DirectCast(entry.Value, String))
            Next
        End Sub
        Public Sub GetObjectData(info As SerializationInfo, context As StreamingContext) Implements ISerializable.GetObjectData
            For Each key As String in dict.Keys
                info.AddValue(key, dict.Item(key))
            Next
        End Sub
    End Class
    

    Called with:

    string MyJsonString = "{ \"key1\": \"value1\", \"key2\": \"value2\"}";
    System.Runtime.Serialization.Json.DataContractJsonSerializer dcjs = new
      System.Runtime.Serialization.Json.DataContractJsonSerializer(
        typeof(StringStringDictionary));
    System.IO.MemoryStream ms = new
      System.IO.MemoryStream(Encoding.UTF8.GetBytes(MyJsonString));
    StringStringDictionary myfields = (StringStringDictionary)dcjs.ReadObject(ms);
    Response.Write("Value of key2: " + myfields.dict["key2"]);
    

    Sorry for the mix of C# and VB.NET…

提交回复
热议问题