[英]Json.net Deserialization fails when object is empty
Json.net Deserialization is failing when my JSON string contains an empty object value where it expects a string. 当我的JSON字符串在期望字符串的地方包含一个空对象值时,Json.net反序列化失败。
public class MyObj
{
public Labels labels { get; set; }
public Type type { get; set; }
public int value { get; set; }
[JsonConverter(typeof(SliderTextConverter))]
public string text { get; set; }
}
Sometimes 'text' is equal to an empty object in the source JSON string, '{}'. 有时,“文本”等于源JSON字符串“ {}”中的空对象。 The JSON.net deserializer seems to bomb because of this. 因此,JSON.net反序列化器似乎炸毁了。 So I am attempting to create a custom JsonConverter to get around this. 因此,我试图创建一个自定义JsonConverter来解决此问题。
public class SliderTextConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if(reader.Value == null)
{
return null;
}
return serializer.Deserialize<string>(reader);
}
public override bool CanConvert(Type objectType)
{
return true;
}
}
I am checking to see if the value is null and then just returning 'null' This does not work. 我正在检查该值是否为null,然后仅返回'null'。这不起作用。 I have also tried to just return, "". 我还尝试过返回“”。 Both result in the same error: 两者都导致相同的错误:
Unexpected token while deserializing object: EndObject. 反序列化对象时意外的标记:EndObject。 Path 'data.MyObj[5].text; 路径'data.MyObj [5] .text;
What is the correct way to ignore/handle these empty objects in my source json? 在我的源json中忽略/处理这些空对象的正确方法是什么?
Thanks! 谢谢!
This post on Json.NET seems to reference the same problem: http://james.newtonking.com/archive/2012/04/11/json-net-4-5-release-2-serializable-support-and-bug-fixes.aspx Json.NET上的此帖子似乎引用了相同的问题: http : //james.newtonking.com/archive/2012/04/11/json-net-4-5-release-2-serializable-support-and-bug -fixes.aspx
Changes:
Fix - Fixed deserializing a null string throwing a NullReferenceException
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.