Reputation: 625
I get such JSON and want to deserialize it into my C# object. But this ends up in an error that cannot deserialize. Can I get help in fixing this?
public class UserDto {
public string Id { get; set; }
public string Name { get; set; }
public List<string> Permissions { get; set; }
}
Above is the model object for binding the API output
HttpResponseMessage response = await client.GetAsync($"/users");
if (!response.IsSuccessStatusCode || response.Content == null) {
return null;
}
string result = await response.Content.ReadAsStringAsync();
UserDto users = await response.Content.ReadAsJsonAsync<UserDto>();
List<UserDto> x2 = JsonConvert.DeserializeObject<List<UserDto>>(result);
The above getasync
method gives me the below result and i am trying to deserialize it to object.
{
"users": [{
"id": "1",
"name": "ttest",
"permissions": [
"add",
"edit",
"delete"
]
}]
}
Error:
Cannot deserialize the current JSON object (e.g. {"name":"value"})
into type 'System.Collections.Generic.List`1[****.Models.UserDto]'
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.
I get such JSON and want to deserialize it into my C# object. But this ends up in an error that cannot deserialize. Can I get help in fixing this?
Upvotes: 0
Views: 1864
Reputation: 16049
In your JSON, Users
JArray is inside a JObject, so to convert your JSON string you need List<User>
inside a RootObject
class like,
public class User
{
public string id { get; set; }
public string name { get; set; }
public List<string> permissions { get; set; }
}
public class Root
{
public List<User> users { get; set; }
}
Deserialize like,
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(result);
Upvotes: 1