您可以使用以下自定义转换器:
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
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)