Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReadAsAsync got null values from Json data?

I have a class

public class C
{
    public int Id { get; set; }
    public SqlXml Range { get; set; } // System.Data.SqlTypes.SqlXml
}

And the following code is used to read the data from web api.

    List<C> cs = null;
    var response = await client.GetAsync(url);
    if (response.IsSuccessStatusCode)
    {
        cs = await response.Content.ReadAsAsync<List<C>>(); // cs[..].Range is null
    }

The following is some sample Json file returned from the Web API.

[{"id":0,"range":{"isNull":false,"value":"<Range>....</Range>"}},
 {"id":1,"range":{"isNull":false,"value":"<Range>...</Range>"}},
 {"id":2,"range":{"isNull":false,"value":"<Range>....</Range>"}}]

However, the variable cs got the following values. The Id values are correct. But all the Ranges got null values?

0, null
1, null
2, null

The debugger shows cs[...].Range.IsNull is true.

like image 430
ca9163d9 Avatar asked Sep 13 '26 08:09

ca9163d9


1 Answers

The properties of System.Data.SqlTypes.SqlXml are read only. When the deserializer tries to create objects of that type it will fail while trying to set the properties.

Create you own class to hold the desired values

public class Range {
    public bool IsNull { get; set; }
    public string Value { get; set; }
}

public class C {
    public int Id { get; set; }
    public Range Range { get; set; }
}

This should now allow the Range values to be properly populated

like image 57
Nkosi Avatar answered Sep 15 '26 23:09

Nkosi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!