JSON反序列化器返回NULL值

and*_*odd 1 c# json

我试图通过C#控制台应用程序使用REST API,并且我已经获得了web服务以返回JSON文件,其格式为:

{"status":200,"result":{"postcode":"SW1W0DT","quality":1,"eastings":528813,"northings":178953,"country":"England","nhs_ha":"London","longitude":-0.145828,"latitude":51.494853,"european_electoral_region":"London","primary_care_trust":"Westminster","region":"London","lsoa":"Westminster 023E","msoa":"Westminster 023","incode":"0DT","outcode":"SW1W","parliamentary_constituency":"Cities of London and Westminster","admin_district":"Westminster","parish":"Westminster, unparished area","admin_county":null,"admin_ward":"Warwick","ccg":"NHS Central London (Westminster)","nuts":"Westminster","codes":{"admin_district":"E09000033","admin_county":"E99999999","admin_ward":"E05000647","parish":"E43000236","parliamentary_constituency":"E14000639","ccg":"E38000031","nuts":"UKI32"}}}
Run Code Online (Sandbox Code Playgroud)

我创建了一个类AddressInfo如下:

public class AddressInfo {
    public string postcode { get; set; }
    public int quality { get; set; }
    public int eastings { get; set; }
    public int northings { get; set; }
    public string country { get; set; }
    public string nhs_ha { get; set; }
    public string admin_county { get; set; }
    public string admin_district { get; set; }
    public string admin_ward { get; set; }
    public double longitude { get; set; }
    public double latitude { get; set; }
    public string parliamentary_constituency { get; set; }
    public string european_electoral_region { get; set; }
    public string primary_care_trust { get; set; }
    public string region { get; set; }
    public string parish { get; set; }
    public string lsoa { get; set; }
    public string msoa { get; set; }
    public string ccg { get; set; }
    public string nuts { get; set; }
    public object codes { get; set; } 
}
Run Code Online (Sandbox Code Playgroud)

调用API并获取值的代码是:

string strJSON = string.Empty;

strJSON = rClient.makeRequest();
Console.Write(strJSON);

AddressInfo AI = new AddressInfo();
AI = Newtonsoft.Json.JsonConvert.DeserializeObject<AddressInfo>(strJSON);
Run Code Online (Sandbox Code Playgroud)

但是,当我调试时,AI将值返回为"NULL".

谢谢

Kwi*_*ten 5

请注意,您的JSON具有嵌套结构.AddressInfo包含在其result属性中,它不在顶层.

你反序列化整个JSON响应的实际类结构应该是这样的(我称之为类JsonResponse但你可以随意命名):

class JsonResponse{
    public int status { get; set; }
    public AddressInfo result { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后像这样反序列化:

JsonResponse res = JsonConvert.DeserializeObject<JsonResponse>(strJSON);
AddressInfo addressInfo = res.result;
Run Code Online (Sandbox Code Playgroud)