c# - 将 JSON 对象反序列化为 .NET HashSet

标签 c# .net json serialization json.net

这是原始 JSON 数据的示例:

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

我想将数据反序列化为:

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

Standards字段实际上有 Dictionary<String, String>类型。不知何故键和值总是相等的。由于类型不兼容,我正在寻找一种方法来对此字段执行自定义反序列化。

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

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

最佳答案

您可以使用自定义 JsonConverter 来处理这个问题.这是您需要的代码:

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] 属性添加到您的模型中,如下所示:

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

然后,只要像往常一样反序列化就可以了:

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

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

关于c# - 将 JSON 对象反序列化为 .NET HashSet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39592254/

相关文章:

c# - 我可以使用 WCF 接口(interface)作为 MVVM 模型吗?

c# - 以编程方式 "hello world"ASP.NET MVC 中的默认服务器端打印机

json - 为 select() 找到的元素设置一个值,但返回整个 json

javascript - Dust.js 输出 JSON 键

java - 从android的webview访问JSON响应

c# - 将三个文件合并为一个大文件

c# - 如何在不破坏应用程序引用的情况下从部署项目中重新定位程序集?

C# 公共(public)库

c# - 向上舍入 c# TimeSpan 到 5 分钟

c# - 应用程序关闭,恕不另行通知