2014-01-05 3 views
1

Я получил ответ в формате JSON, например:JSON Deserialize Выпуск

JSON

"meta": { 
    "code": 200 
    }, 
    "data": [ 
    { 
     "username": "username here", 
     "bio": "bio here", 
     "website": "web site here", 
     "profile_picture": "link here", 
     "full_name": "name here", 
     "id": "id here" 
    } 
    ] 

C#

public class Meta 
{ 
    public int code { get; set; } 
} 

public class Datum 
{ 
    public string username { get; set; } 
    public string bio { get; set; } 
    public string website { get; set; } 
    public string profile_picture { get; set; } 
    public string full_name { get; set; } 
    public string id { get; set; } 
} 

public class RootObject 
{ 
    public Meta meta { get; set; } 
    public List<Datum> data { get; set; } 
} 

Я написал этот код:

JObject instaCall = JObject.Parse(response); 
Datum searchResult = instaCall["data"].ToObject<Datum>(); 

но выдает ошибку:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'WindowsFormsApplication1.functions.response+Datum' 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.

ответ

2

Как о чем-то вроде этого:

var o = JsonConvert.DeserializeObject<RootObject>(response); 
Datum searchResult = o.data.FirstOrDefault(); 

if (searchResult != null) 
{ 
    // awesome 
} 
1

Поскольку ошибка пытается сказать вам, instaCall["data"] массив.
Вы не можете прочитать это в одном объекте.

+0

Как мне читать это? – user3158925

+0

сделать это в foreach? – user3158925