2016-09-30 7 views
2

У меня есть JSON ответ так:Deserialize список объектов из ответа Json Http

{ 
    "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); 
    } 
} 

Но я получаю эту ошибку:

Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.IEnumerable`1[TestREST.Program+RestResponse]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.

Path 'RestResponse', line 2, position 19.

Что мне делать с этим, чтобы моя работа по десерилизации?

+0

Пожалуйста, ваши 'Address' класс. –

+0

Обновлено с помощью класса адресов – Pouyan

ответ

3

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

У Json, который у меня есть, нет «\» этого. У меня есть одна и та же строка, но без обратных косых черт, и она не работает. – Pouyan

+0

@Pouyan '' 'должен избегать символов' '', потому что я просто написал строку внутри самого кода C# * (мой пример не получает json-данные с сервера) * ... отлично работает btw – Jim

Смежные вопросы