Reputation: 21
I've got a problem with Deserializing a JSON Object. This is the JSON I have:
{
"resource": [{
"ClienteNome": "DOUGLAS DA SILVA BENEDITO",
"ClienteStatus": 0
}, {
"ClienteNome": "MARCO AURELIO DE SÁ GONÇALVES",
"ClienteStatus": 1
}, {
"ClienteNome": "MATHEUS CELESTINO CANDIDO",
"ClienteStatus": 2
}]
}
I'm trying to deserialize it this way
public static async Task<List<Model.ClientesOnline>> GetAsync()
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("X-DreamFactory-Api-Key", "36fda24fe5588fa4285ac6c6c2fdfbdb6b64699774c9bf777f706d05a88");
string json = await client.GetStringAsync("http://api-u16.cloudapp.net/api/v2/nova207/_table/vw_clientes_online");
var clientesonline = JsonConvert.DeserializeObject<List<Model.ClientesOnline>>(json);
return clientesonline;
}
}
model
namespace NovaCloud.Model
{
class ClientesOnline : INotifyPropertyChanged
{
[JsonProperty("Resorces")]
private string clientenome;
public string ClienteNome { get { return clientenome; }
set
{
clientenome = value;
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ClienteNome)));
}
}
private string clientestatus;
public string ClienteStatus { get { return clientestatus; }
set
{
clientestatus = value;
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ClienteStatus)));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
Error message
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,Linker.Class.alternatives]' 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.
I've tried in several ways
Upvotes: 2
Views: 73
Reputation: 1261
Your model is wrong, you are expecting an object not a list, This is what the model should like:
public class Resource
{
public string ClienteNome { get; set; }
public int ClienteStatus { get; set; }
}
public class ClientsOnline
{
public List<Resource> resource { get; set; }
}
And when you deserialize you should do something like this:
var clientsOnline= JsonConvert.DeserializeObject<ClientesOnline>(json);
Upvotes: 3