简体   繁体   中英

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 Range s got null values?

0, null
1, null
2, null

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

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

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