gpt4 book ai didi

C# 无法使用数组反序列化复杂的 Json 对象

转载 作者:行者123 更新时间:2023-11-30 19:53:42 32 4
gpt4 key购买 nike

所以我使用HttpClient()从 web api 获取 Json 对象。该对象包含一个国家/地区所有省份的列表。

这段代码调用了json反序列化:

rj = JsonConvert.DeserializeObject<RajaOngkirCity>(response);

响应是这样的:

{
"rajaongkir": {
"query": {
"key": "xxxxxxxxxxxxxxxxxxxxx"
},
"status": {
"code": 200,
"description": "OK"
},
"results": [{
"province_id": "1",
"province": "Bali"
},
{
"province_id": "2",
"province": "Bangka Belitung"
},
.....]
}
}

这些是我的类(class):

public class RajaOngkirState
{
[JsonProperty("rajaongkir")]
public RajaOngkirStateResult RajaOngkir { get; set; }
}

public class RajaOngkirStateResult
{
[JsonProperty("query")]
public RajaOngkirStateQuery StateQuery { get; set; }

[JsonProperty("status")]
public RajaOngkirStateStatus Status { get; set; }

[JsonProperty("results")]
public RajaOngkirStateResults Results { get; set; }
}

public class RajaOngkirStateQuery
{
[JsonProperty("key")]
public string Key { get; set; }
}

public class RajaOngkirStateStatus
{
[JsonProperty("code")]
public int Code { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
}

public class RajaOngkirStateResults
{
public List<RajaOngkirStateList> States { get; set; }
}

public class RajaOngkirStateList
{
[JsonProperty("province_id")]
public int ProvinceId { get; set; }
[JsonProperty("province")]
public string Province { get; set; }
}

似乎rajaongkir.results这导致了我的问题。

以下是我尝试过的:

  1. 我尝试更改 province_id键入字符串,但仍然错误。
  2. 我试图改变 List<RajaOngkirStateList> States进入Dictionary<string, RajaOngkirStateList>但仍然出错。

我得到的错误:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'ECommerce.ShippingMethod.RajaOngkir.RajaOngkirStateResults' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. Path 'rajaongkir.results', line 1, position 118.

最佳答案

目前您的 Results 属性声称是一个包含数组的对象 - 就好像您的 JSON 看起来像这样:

"results": {
states: [{
"province_id": "1",
"province": "Bali"
},
{
"province_id": "2",
"province": "Bangka Belitung"
}
]}

相反,JSON 中的 results 属性列表。

所以您需要做的就是完全删除 RajaOngkirStateResults 类,并将您的 Results 属性更改为:

[JsonProperty("results")]
public List<RajaOngkirStateList> Results { get; set; }

我个人将 RajaOngkirStateList 重命名为 RajaOngkirState,因为它不是列表,但这是另一回事。

关于C# 无法使用数组反序列化复杂的 Json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46924535/

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