Json.net反序列化null guid案例
我正在使用包含Guid类型的私有字段和该字段的公共属性的Json.NET
反序列化对象。 当我的Guid
的值在我的json中为null时,我想将Guid.Empty
分配给我的字段。
public class MyClass { private Guid property; public Guid Property { get { return property; } set { if (value == null) { property = Guid.Empty; } else { property = value; } } } }
但是deserializer
想要访问私有字段,因为当我尝试反序列化时出现此错误:
将值{null}转换为类型’System.Guid’时出错。 路径'[0] .property’,第6行,第26位。
如何让它忽略私有字段并使用公共属性?
Json.NET拒绝为Guid
设置null
值,因为它是一个不可为空的值类型。 尝试在立即窗口中键入(Guid)null
,您将看到一条错误消息,指示无法在.Net中进行此转换。
要解决此问题,您有以下几种选择:
-
创建一个
Guid?
可空的代理属性。 只要它具有[JsonProperty]
属性,它就可以是私有的:public class MyClass { [JsonIgnore] public Guid Property { get; set; } [JsonProperty("Property")] Guid? NullableProperty { get { return Property == Guid.Empty ? null : (Guid?)Property; } set { Property = (value == null ? Guid.Empty : value.Value); } } }
-
创建一个将
null
Json标记转换为默认Guid
值的JsonConverter
:public class NullToDefaultConverter
: JsonConverter where T : struct { public override bool CanConvert(Type objectType) { return objectType == typeof(T); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var token = JToken.Load(reader); if (token == null || token.Type == JTokenType.Null) return default(T); return token.ToObject(objectType); } // Return false instead if you don't want default values to be written as null public override bool CanWrite { get { return true; } } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (EqualityComparer .Default.Equals((T)value, default(T))) writer.WriteNull(); else writer.WriteValue(value); } } 然后将其应用于您的类型,如下所示:
public class MyClass { [JsonConverter(typeof(NullToDefaultConverter
))] public Guid Property { get; set; } } 或者,您可以通过将转换器添加到
JsonSerializerSettings.Converters
,将转换器应用于T
类型的所有值。 并且,要在全局注册这样的转换器,请参阅例如在Json.Net中为控制台应用程序全局注册自定义JsonConverter , 如何在MVC 4 Web API中为Json.NET设置自定义JsonSerializerSettings? 对于Web API,或者设置JsonConvert.DefaultSettings,asp net core 2.0不能像 ASP.NET Core 那样工作 。上述就是C#学习教程:Json.net反序列化null guid案例分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/986628.html