我在反序列化 JSON 对象时遇到问题。这是我的 JSON:
{
"resource": [{
"ClienteNome": "DOUGLAS DA SILVA BENEDITO",
"ClienteStatus": 0
}, {
"ClienteNome": "MARCO AURELIO DE SÁ GONÇALVES",
"ClienteStatus": 1
}, {
"ClienteNome": "MATHEUS CELESTINO CANDIDO",
"ClienteStatus": 2
}]
}
我正在尝试以这种方式反序列化它
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;
}
}
型号
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;
}
}
错误信息
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.
我尝试过多种方法
最佳答案
你的模型是错误的,你期望的是一个对象而不是列表,这就是模型应该喜欢的:
public class Resource
{
public string ClienteNome { get; set; }
public int ClienteStatus { get; set; }
}
public class ClientsOnline
{
public List<Resource> resource { get; set; }
}
当你反序列化时,你应该这样做:
var clientsOnline= JsonConvert.DeserializeObject<ClientesOnline>(json);
关于json - 如何将Json反序列化为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40631942/