gpt4 book ai didi

c# - 返回 NULL 值的 JSON 反序列化器

转载 作者:太空宇宙 更新时间:2023-11-03 17:19:42 25 4
gpt4 key购买 nike

我正在尝试通过 C# 控制台应用程序使用 REST API,并且我已经让网络服务返回 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"}}}

我创建了一个类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; }
}

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

string strJSON = string.Empty;

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

AddressInfo AI = new AddressInfo();
AI = Newtonsoft.Json.JsonConvert.DeserializeObject<AddressInfo>(strJSON);

但是,当我调试时,AI 将值返回为“NULL”。

谢谢

最佳答案

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

反序列化整个 JSON 响应的实际类结构应如下所示(我将类命名为 JsonResponse 但您可以随意命名):

class JsonResponse{
public int status { get; set; }
public AddressInfo result { get; set; }
}

然后像这样反序列化:

JsonResponse res = JsonConvert.DeserializeObject<JsonResponse>(strJSON);
AddressInfo addressInfo = res.result;

关于c# - 返回 NULL 值的 JSON 反序列化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51321588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com