c#JSON序列化使用值而不是属性名称



我正在处理一个JSON驱动的项目,我想为SessionManager对象提供一个动态的permissionst列表。虽然我可以使用一组键值对来获得权限,但我想知道是否可以删除属性名称,以便Permission值,IsAllowed值。

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

当我生成JSON时,它会输出一组权限:

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

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

{
    "CreateUsers": false
},

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

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

用法:

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

示例JSON:

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

相反的做法也应该很好。

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

相关内容

  • 没有找到相关文章

最新更新