问题描述
我正在开发一个 JSON 驱动的项目,我想为 SessionManager
对象提供一个动态的权限列表.虽然我可以使用一组键值对来获取权限,但我想知道是否可以删除属性名称,以便 key 是 Permission
值和 value 是 IsAllowed
值.
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}
};
}
}
当我生成 JSON 时,它会输出一组权限:
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; }
}
}
用法:
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
这篇关于c# JSON序列化使用值而不是属性名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!