本文介绍了将JSON对象反序列化为.NET HashSet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是原始JSON数据的示例:

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; }
}

Standards 字段实际上具有 Dictionary< String,String> 类型.键和值总是以某种方式相等.由于类型不兼容,我正在寻找一种对该字段执行自定义反序列化的方法.

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.

首选基于JSON.NET库的解决方案.

A solution based on JSON.NET library is preferred.

P.S .:我无法控制数据序列化过程.

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

推荐答案

您可以使用自定义的 JsonConverter .这是您需要的代码:

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);
    }
}

要使用转换器,请在模型中添加 [JsonConverter] 属性,如下所示:

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);

这是一个往返演示: https://dotnetfiddle.net/tvHt5Y

这篇关于将JSON对象反序列化为.NET HashSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:19