JSON Deserializer返回NULL值

时间:2018-07-13 09:09:54

标签: c# json

我正在尝试通过C#控制台应用程序使用REST API,并且我已经尽力让Web服务返回JSON文件,格式为:

SELECT movies.*, AVG(movie_ratings.rating) AS rating
FROM movies
LEFT JOIN movie_ratings ON movies.id = movie_ratings.id
GROUP BY movies.id
ORDER BY rating DESC

我创建了一个{"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

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

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; } 
}

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

谢谢

4 个答案:

答案 0 :(得分:5)

请注意,您的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;

答案 1 :(得分:4)

您遗漏了这样一个事实,您需要一个具有属性int statusAdressInfo result的外部类。

答案 2 :(得分:2)

您的JSON是嵌套的。结果是一个嵌套对象。这就是为什么您遇到此问题。

答案 3 :(得分:2)

您无需创建单独的类来反序列化整个响应,可以动态完成此操作以获得所需的结果:

var source = "(your JSON");
dynamic data = JObject.Parse(source);   
var d = JsonConvert.SerializeObject(data.result);
AddressInfo account = JsonConvert.DeserializeObject<AddressInfo>(d);