我有我的JSON响应:
{
"Adddress": [
{
"Country": "United States",
"City": "Irmo",
"Line1": "103 Kinley Rd",
"Line2": null,
"PostalCode": "20063",
"State": "SC",
"AddressCode": "BILL-01"
},
{
"Country": "United States",
"City": "Irmo",
"Line1": "1098 Kanley Road",
"Line2": "Building B",
"PostalCode": "29063",
"State": "SC",
"AddressCode": "SHIP-01"
}]
}
这是我的地址类:
[JsonObject()]
public class Address
{
public string AddressCode { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Country { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
public string City { get; set; }
}
我有这个C#代码将这个http响应反序列化到我的对象列表中:
HttpResponseMessage response = client.GetAsync(urlParameters).Result; // Blocking call!
if (response.IsSuccessStatusCode)
{
var dataObjects = response.Content.ReadAsAsync<Adddress>().Result;//JsonConvert.DeserializeObject<List<RestResponse>>(response.Content.ReadAsStringAsync().Result);//
foreach (var d in dataObjects)
{
Console.WriteLine("{0}", d.Country);
}
}
但是我收到了这个错误:
附加信息:无法将当前JSON对象(例如{“name”:“value”})反序列化为类型'System.Collections.Generic.IEnumerable`1 [TestREST.Program + RestResponse]',因为该类型需要JSON数组(例如[1,2,3])正确反序列化。
要修复此错误,请将JSON更改为JSON数组(例如 [1,2,3])或更改反序列化类型,使其成为正常的.NET type(例如,不是像整数这样的基本类型,不是集合类型 像数组或List一样,可以从JSON对象反序列化。 JsonObjectAttribute也可以添加到类型中以强制它 从JSON对象反序列化。
路径'RestResponse',第2行,第19位。
我应该怎样做才能使我的去除药物?
答案 0 :(得分:5)
Adddress
是单一的,你进入的json是一个地址数组(所以多于一个),你必须将其反序列化为例如AddressList
包含多个地址
string json = "{\"Adddress\":[{\"Country\":\"United States\",\"City\":\"Irmo\",\"Line1\":\"103 Kinley Rd\",\"Line2\":null,\"PostalCode\":\"20063\",\"State\":\"SC\",\"AddressCode\":\"BILL - 01\"},{\"Country\":\"United States\",\"City\":\"Irmo\",\"Line1\":\"1098 Kanley Road\",\"Line2\":\"Building B\",\"PostalCode\":\"29063\",\"State\":\"SC\",\"AddressCode\":\"SHIP - 01\"}]}";
var dataObjects = JsonConvert.DeserializeObject<AddressList>(json);
foreach (var d in dataObjects.Adddress)
{
Console.WriteLine("{0}", d.Country);
}
类:
public class Adddress
{
[JsonProperty("Country")]
public string Country { get; set; }
[JsonProperty("City")]
public string City { get; set; }
[JsonProperty("Line1")]
public string Line1 { get; set; }
[JsonProperty("Line2")]
public string Line2 { get; set; }
[JsonProperty("PostalCode")]
public string PostalCode { get; set; }
[JsonProperty("State")]
public string State { get; set; }
[JsonProperty("AddressCode")]
public string AddressCode { get; set; }
}
public class AddressList
{
[JsonProperty("Adddress")]
public IList<Adddress> Adddress { get; set; }
}