I am retrieving the JSON body from an API. I want to deserialize the Json into class and get the specific data I want to append into Picker (Xamarin Forms). I keep on getting error and I am not sure how to resolve this issue. This is my first time doing deserialize so I hope someone can help me on this! Thank you
Error
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'App123.UserDetails[]' 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.
Path 'Error', line 1, position 9.'
JSON
{
"Error": null,
"Success": true,
"Data": {
"Message": "Success",
"NextPrompt": null,
"NextDefaultValue": "",
"IsFinished": false,
"ReturnData": [
{
"User": "M0001",
"Role": "Admin",
"Password": "abc2020",
"Contact": "98780101",
"Department": "HR"
},
{
"User": "M1043",
"Role": "Director",
"Password": "zxy2020",
"Contact": "91235678",
"Department": "Finance"
}
]
}
}
Class
public class UserDetails
{
public class Rootobject
{
public object Error { get; set; }
public bool Success { get; set; }
public Data Data { get; set; }
}
public class Data
{
public string Message { get; set; }
public object NextPrompt { get; set; }
public string NextDefaultValue { get; set; }
public bool IsFinished { get; set; }
public Returndata[] ReturnData { get; set; }
}
public class Returndata
{
public string User { get; set; }
public string Role { get; set; }
public string Password { get; set; }
public string Contact { get; set; }
public string Department { get; set; }
}
}
Code
(code on API connection)
var response = await client2.SendAsync(request).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
var responsebody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
string text = responsebody.ToString();
string[] strText = text.Split(new[] { ',', ':', '}', '{', ']', '[', '\\', '"' }, StringSplitOptions.RemoveEmptyEntries);
UserDetails[] userdetails = JsonConvert.DeserializeObject<UserDetails[]>(text);
UserPicker.ItemsSource = userdetails;