简体   繁体   中英

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.

 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, '{}'. The JSON.net deserializer seems to bomb because of this. So I am attempting to create a custom JsonConverter to get around this.

 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. I have also tried to just return, "". Both result in the same error:

Unexpected token while deserializing object: EndObject. Path 'data.MyObj[5].text;

What is the correct way to ignore/handle these empty objects in my source 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

Changes:    
    Fix - Fixed deserializing a null string throwing a NullReferenceException 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM