加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 将json反序列化为object:包装器类解决方法

发布时间:2020-12-15 22:19:03 所属栏目:百科 来源:网络整理
导读:这是我的json { "accessType":"Grant","spaces":[{"spaceId":"5c209ba0-e24d-450d-8f23-44a99e6ae415"}],"privilegeId":"db7cd037-6503-4dbf-8566-2cca4787119d","privilegeName":"PERM_RVMC_DEV","privilegeDescription":"RVMC Dev","privilegeType":"Permi
这是我的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创建一个包装类来解决这个问题

public class Space
{
    public Guid spaceId;   
}

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

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

解决方法

您可以使用简单的JsonConverter类将空间对象数组展平为GUID列表,从而消除对包装类的需要.

以下是转换器所需的代码:

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

要使用它,请使用[JsonConverter]属性注释ProfilePrivilege类中的Spaces属性,如下所示:

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

然后,当你反序列化时,一切都应该“正常工作”.

完整演示:https://dotnetfiddle.net/EaYgbe

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读