Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize JSON object as .NET HashSet

Here's an example of raw JSON data:

{ "Standards": { "1": "1" } }

I want to deserialize the data to:

public class Model
{
    public HashSet<String> Standards { get; set; }
}

The Standards field actually has the Dictionary<String, String> type. Somehow the keys and values are always equal. As the types are incompatible, I'm looking for a way to perform a custom deserialization of this field.

A solution based on JSON.NET library is preferred.

P.S.: I have no control over the data serialization process.

like image 321
shadeglare Avatar asked Sep 20 '16 10:09

shadeglare


1 Answers

You can handle this with a custom JsonConverter. Here is the code you would need:

public class CustomHashSetConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(HashSet<string>);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JObject jo = JObject.Load(reader);
        return new HashSet<string>(jo.Properties().Select(p => p.Name));
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        HashSet<string> hashSet = (HashSet<string>)value;
        JObject jo = new JObject(hashSet.Select(s => new JProperty(s, s)));
        jo.WriteTo(writer);
    }
}

To use the converter, add a [JsonConverter] attribute to your model like this:

public class Model
{
    [JsonConverter(typeof(CustomHashSetConverter))]
    public HashSet<string> Standards { get; set; }
}

Then, just deserialize as normal and it should work:

Model model = JsonConvert.DeserializeObject<Model>(json);

Here is a round-trip demo: https://dotnetfiddle.net/tvHt5Y

like image 163
Brian Rogers Avatar answered Oct 12 '22 23:10

Brian Rogers