c# JSON Serialization Use Value Instead of Property Name

可紊 提交于 2019-12-29 00:44:28

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/29173196/c-sharp-json-serialization-use-value-instead-of-property-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!