Reputation: 39
I have the next response from an API
{
"ArticleSpecification": [
{
"Name": "SomeName",
"Description ": "Description ",
"Label": "SomeLabel",
}
]
}
Then I try to Deserialize the object using my class
public class ArticleSpecification
{
[JsonProperty("Description")]
public string Description { get; set; }
[JsonProperty("Label")]
public string Label { get; set; }
[JsonProperty("Name")]
public string Name { get; set; }
}
The deserialize section looks like this
if (responseMessage.IsSuccessStatusCode)
{
var json = responseMessage.Content.ReadAsStringAsync().Result;
List<ArticleSpecification> articles = JsonConvert.DeserializeObject<List<ArticleSpecification>(json);
}
The result is the next :
Unhandled exception. Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Program+ArticleSpecification]' 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<T>) 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
Upvotes: 0
Views: 257
Reputation: 84
The response from API is an object, not the array.
Your response actually is an object, which has the property: ArticleSpecification which is the array. Example of class for such reponse:
class APIResponse {
public ArticleSpecification[] ArticleSpecification { get; set; }
}
Then you can deserialize response:
var response = JsonConvert.DeserializeObject<APIResponse>(json);
List<ArticleSpecification> articles = new List<ArticleSpecification>(response.ArticleSpecification);
Something among those lines.
Upvotes: 3