【问题标题】:How to deserialize Json to object如何将 Json 反序列化为对象
【发布时间】:2016-11-16 12:14:56
【问题描述】:

我在反序列化 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;

    }
}

错误信息

无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型 'System.Collections.Generic.Dictionary`2[System.String,Linker.Class.alternatives]' 因为该类型需要一个 JSON 对象(例如 {"name":"value"}) 正确反序列化。要修复此错误,请将 JSON 更改为 JSON 对象(例如 {"name":"value"})或将反序列化类型更改为 实现集合接口的数组或类型(例如 ICollection, IList) 之类的可以从 JSON 反序列化的 List 大批。 JsonArrayAttribute 也可以添加到类型中以强制它 从 JSON 数组反序列化。

我尝试了几种方法

【问题讨论】:

  • 你必须改变你的模型类。如果您不确定您的模型是否正确,请使用 json2csharp 检查它。 (json2csharp.com)

标签: json serialization


【解决方案1】:

你的模型错了,你期待的是一个对象而不是一个列表,这就是模型应该的样子:

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    相关资源
    最近更新 更多