Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

c# JSON Serialization Use Value Instead of Property Name

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
},
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...