将json反序列化为对象:包装器类变通办法 [英] Deserializing json into object: wrapper class workaround

查看:79
本文介绍了将json反序列化为对象:包装器类变通办法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的json

{
    "accessType":"Grant",
    "spaces":[{"spaceId":"5c209ba0-e24d-450d-8f23-44a99e6ae415"}],
    "privilegeId":"db7cd037-6503-4dbf-8566-2cca4787119d",
    "privilegeName":"PERM_RVMC_DEV",
    "privilegeDescription":"RVMC Dev",
    "privilegeType":"Permission"
}

这是我的课:

public class ProfilePrivilege
{
    public AccessType AccessType { get; set; }
    public Guid PrivilegeId { get; set; }
    public string PrivilegeName { get; set; }
    public string PrivilegeDescription { get; set; }
    public PrivilegeType PrivilegeType { get; set; }
    public List<Guid> spaces;
}

当spaces数组不为null时,我将得到反序列化错误.我可以通过简单地为Guid创建包装类来解决这个问题

When the spaces array is not null I get an error deserializing. I can get around this by simply creating a wrapper class for Guid

public class Space
{
    public Guid spaceId;   
}

,然后在Privilege类中有一个List<Space>而不是List<Guid>,这一切都很好.但是我想知道是否有更好的方法可以做到这一点,因为我不想为此而准备一个多余的包装器类.因此,有什么简单的方法可以解决此问题,而无需为我的Privilege类型的对象编写自定义反序列化器?

and then instead of List<Guid> I can have a List<Space> in my Privilege class and it's all fine. But I was wondering if there's a better way to do this as I don't want to have a redundant wrapper class just for that. So is there any easy way to get around this without writing a custom deserializer for my Privilege type objects ?

我正在使用JSON.Net btw反序列化.

I'm deserializing with JSON.Net btw.

推荐答案

您可以使用简单的JsonConverter类将spaces对象数组展平为一个GUID列表,从而不需要包装类.

You can use a simple JsonConverter class to flatten the spaces object array to a list of GUIDs, thereby eliminating the need for the wrapper class.

这是转换器所需的代码:

Here is the code you would need for the converter:

class SpaceListConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(List<Guid>));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return JArray.Load(reader)
                     .Children<JObject>()
                     .Select(jo => Guid.Parse((string)jo["spaceId"]))
                     .ToList();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

要使用它,请在ProfilePrivilege类中的Spaces属性上标注一个[JsonConverter]属性,如下所示:

To use it, annotate the Spaces property in your ProfilePrivilege class with a [JsonConverter] attribute like this:

public class ProfilePrivilege
{
    ...
    [JsonConverter(typeof(SpaceListConverter))]
    public List<Guid> Spaces;
    ...
}

然后,当您反序列化时,一切都应该正常工作".

Then, when you deserialize, everything should "just work".

此处的完整演示: https://dotnetfiddle.net/EaYgbe

这篇关于将json反序列化为对象:包装器类变通办法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆