Quantcast
Channel: How can I deserialize JSON to a simple Dictionary in ASP.NET? - Stack Overflow
Viewing all articles
Browse latest Browse all 23

Answer by richardtallent for How can I deserialize JSON to a simple Dictionary in ASP.NET?

$
0
0

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:

VB.NET:

<Serializable()> 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 SubEnd Class

same on C#:

public class StringStringDictionary : ISerializable{    public System.Collections.Generic.Dictionary<string, string> dict;    public StringStringDictionary()    {        dict = new System.Collections.Generic.Dictionary<string, string>();    }    protected StringStringDictionary(SerializationInfo info, StreamingContext context)    {        dict = new System.Collections.Generic.Dictionary<string, string>();        foreach (SerializationEntry entry in info)            dict.Add(entry.Name, (string)entry.Value);    }    public void GetObjectData(SerializationInfo info, StreamingContext context)    {        foreach (string key in dict.Keys)            info.AddValue(key, dict[key]);    }}

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…


Viewing all articles
Browse latest Browse all 23

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>