shadeglare shadeglare - 2 months ago 31
JSON Question

Deserialize JSON object as .NET HashSet

There'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 type. Somehow keys and values are always equal. As types are incompatible I'm looking for a way to perform a custom deserialization over this fields.

A solution based on JSON.NET library is prefered.

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

Answer

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

Comments