1
votes

I got a JSON response for example:

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

I wrote this code:

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

but produces an error:

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

2 Answers

2
votes

How about something like this:

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

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

As the error is trying to tell you, instaCall["data"] is an array.
You cannot read that into a single object.