C#JSON序列化使用值,而不是属性名称 [英] c# JSON Serialization Use Value Instead of Property Name

查看:1521
本文介绍了C#JSON序列化使用值,而不是属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个JSON驱动的项目,我想提供是SessionManager 对象,permissionst的动态列表。虽然我可以用键值对的权限的阵列工作,我在想,如果我可以删除的属性名称,以使的的是权限值和的是 IsAllowed 值。

 公共类SessionPermission
{
    公共字符串权限{搞定;组; }
    公共BOOL IsAllowed {搞定;组; }
}
公共类是SessionManager
{
    公共字符串用户名{获得;组; }
    公共字符串密码{搞定;组; }
    公开名单< SessionPermission>权限{搞定;组; }    公共无效SetPermissions()    {
        权限=新的List< SessionPermission>
        {
            新SessionPermission {权限=调用createUsers,IsAllowed = FALSE},
            新SessionPermission {权限=EditUsers,IsAllowed = FALSE},
            新SessionPermission {权限=EditBlog,IsAllowed =真}
        };
    }
}

当我生成JSON它输出权限的数组:

  {
    权限:调用createUsers
    IsAllowed:假的
},

我想知道如何重写序列化,以便它使用的值而不是属性名。

  {
    调用createUsers:假的
},


解决方案

您可以使用以下自定义转换器:

 公共类SessionPermissionConverter:JsonConverter
{
    公众覆盖对象ReadJson(
        JsonReader读卡器,
        键入的objectType,
        对象existingValue,
        JsonSerializer串行)
    {
        VAR OBJ =(JObject)JObject.ReadFrom(读卡器);
        JProperty财产= obj.Properties()FirstOrDefault()。        返回新SessionPermission
        {
            权限= property.Name,
            IsAllowed = property.Value.Value<布尔>()
        };
    }    公共覆盖无效WriteJson(
        JsonWriter作家,
        对象的值,
        JsonSerializer串行)
    {
       SessionPermission权限=(SessionPermission)值;       JObject的obj =新JObject();       OBJ [permission.Permission] = permission.IsAllowed;       obj.WriteTo(作家);
    }    公众覆盖布尔CanConvert(T型)
    {
        返回的typeof(SessionPermission).IsAssignableFrom(T);
    }    公众覆盖布尔的CanRead
    {
        获得{返回true; }
    }
}

用法:

  VAR经理=新SessionManager(中间);
manager.SetPermissions();JSON字符串= JsonConvert.SerializeObject(经理,新SessionPermissionConverter());

样JSON:

  {
  用户名:空,
  密码:空,
  权限:
    {
      调用createUsers:假的
    },
    {
      EditUsers:假的
    },
    {
      EditBlog:真
    }
  ]
}

这应该工作正常去相反的方式为好。

示例: https://dotnetfiddle.net/mfbnuk

I am working on a JSON driven project and I would like to provide the SessionManager object with a dynamic list of permissionst. While I can work with an array of key value pairs for permissions, I was wondering if I could remove the property names so that the key is the Permission value and the value is the IsAllowed value.

public class SessionPermission
{
    public string Permission { get; set; }
    public bool IsAllowed { get; set; }
}


public class SessionManager
{
    public string UserName { get; set; }
    public string Password { get; set; }
    public List<SessionPermission> Permissions { get; set; }

    public void SetPermissions()

    {
        Permissions = new List<SessionPermission>
        {
            new SessionPermission {Permission = "CreateUsers", IsAllowed = false},
            new SessionPermission {Permission = "EditUsers", IsAllowed = false},
            new SessionPermission {Permission = "EditBlog", IsAllowed = true}
        };
    }
}

When I generate JSON it outputs an array of permissions:

{
    "Permission": "CreateUsers",
    "IsAllowed": false
},

I would like to know how to override the serialization so that it uses the values instead of the property names.

{
    "CreateUsers": false
},

解决方案

You could use the following custom converter:

public class SessionPermissionConverter : JsonConverter
{
    public override object ReadJson(
        JsonReader reader,
        Type objectType,
        object existingValue,
        JsonSerializer serializer)
    {
        var obj = (JObject)JObject.ReadFrom(reader);


        JProperty property = obj.Properties().FirstOrDefault();

        return new SessionPermission
        {
            Permission = property.Name,
            IsAllowed = property.Value.Value<bool>()
        };
    }

    public override void WriteJson(
        JsonWriter writer,
        object value,
        JsonSerializer serializer)
    {
       SessionPermission permission = (SessionPermission)value;

       JObject obj = new JObject();

       obj[permission.Permission] = permission.IsAllowed;

       obj.WriteTo(writer);
    }

    public override bool CanConvert(Type t)
    {
        return typeof(SessionPermission).IsAssignableFrom(t);
    }

    public override bool CanRead
    {
        get { return true; }
    }
}

Usage:

var manager = new SessionManager();
manager.SetPermissions();

string json = JsonConvert.SerializeObject(manager, new SessionPermissionConverter());

Sample JSON:

{
  "UserName": null,
  "Password": null,
  "Permissions": [
    {
      "CreateUsers": false
    },
    {
      "EditUsers": false
    },
    {
      "EditBlog": true
    }
  ]
}

It should work fine going the opposite way as well.

Example: https://dotnetfiddle.net/mfbnuk

这篇关于C#JSON序列化使用值,而不是属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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