fravelgue fravelgue - 1 month ago 6
C# Question

Deserialize string property with empty object "{}"

I consume an external service that it responses empty object "{}" for a string property. Could I use some attribute to avoid the exception?

void should_deserialize()
{
var json = "{ \"p1\": {} }";
var res = JsonConvert.DeserializeObject<T1>(json);
}

class T1
{
public string P1 { get; set; }
}

Answer

You can use a hidden backing field to circumvent this problem:

class T1
{
    [JsonProperty("p1")]
    private object _p1;

    [JsonIgnore]
    public string P1
    {
        get { return _p1 as string; }
        set { _p1 = value; }
    }
}

var json = "{ \"p1\": {} }";
// res.P1 is null
var res = JsonConvert.DeserializeObject<T1>(json);

var json2 = "{ \"p1\": \"hello\" }";
// res2.P1 is "hello"
var res2 = JsonConvert.DeserializeObject<T1>(json2);
Comments