Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScriptSerializer : Unable to deserialize object containing HashSet field

Tags:

json

c#

I am trying to deserialize an instance of the following class from a JSON string using JavaScriptSerializer:

public class Filter
{
    public HashSet<int> DataSources { get; set;  }
}

Here is the code I am trying out:

        Filter f = new Filter();

        f.DataSources = new HashSet<int>(){1,2};

        string json = (new JavaScriptSerializer()).Serialize(f);         

        var g= (new JavaScriptSerializer()).Deserialize<Filter>(json);

It errors out with the following message:

Object of type 'System.Collections.Generic.List1[System.Int32]' cannot be converted to type 'System.Collections.Generic.HashSet1[System.Int32]'.

Apparently, the serializer is unable to distinguish between a list and set from JSON representation. What is the solution to this?

Note : I would prefer avoiding the use of external libraries due to constraints at work.

like image 466
Aadith Ramia Avatar asked Mar 02 '26 14:03

Aadith Ramia


1 Answers

What is the solution to this?

Use Json.Net. This code works...

Filter f = new Filter();

f.DataSources = new HashSet<int>() { 1, 2 };

string json = JsonConvert.SerializeObject(f);

var g = JsonConvert.DeserializeObject<Filter>(json);

EDIT

DataContractJsonSerializer seems to work too...

DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(Filter));
var g2 = dcjs.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(json))) as Filter;
like image 195
I4V Avatar answered Mar 05 '26 03:03

I4V