代码之家  ›  专栏  ›  技术社区  ›  johnny 5

Rest Sharp反序列化部分对象

  •  0
  • johnny 5  · 技术社区  · 6 年前

    protected void SetJsonHandler(IRestClient client)
    {
        var jsonHandlerType = "application/json";
        client.ClearHandlers();
        var jsonDeserializer = new JsonNetDeseralizer(JsonSettings);
        client.AddHandler(jsonHandlerType, jsonDeserializer);
    }
    

    我有一个请求,要求获得如下帐户:

    public List<Account> GetAccounts()
    {
        var request = new RestRequest("accounts/", Method.GET, DataFormat.Json);
        var response = this._client.Execute<List<Account>>(request);
    
        this.HandleKnownExceptions(response);
        return response.Data;
    }
    

    我有与物业名称匹配的模型

    public class Balence
    {
        public Double Amount { get; set; }
        public Currency Currency { get; set; }
    }
    
    public class Account
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public bool Primary { get; set; }
        public AccountType Type { get; set; }
        public Balence Balence { get; set; }
        public DateTime CreatedAt { get; set; }
    }
    

    {  
       "pagination":{  
         "ending_before":null,
          //...
       },
       "data":[  
        {  
           "id":"gje99c1e-7081-5784-9a1e-4p302b92312b",
           "name":"ETH Wallet",
           "primary":false,
           "type":"wallet",
           "balance":{  
              "amount":"0.97845347",
              "currency":"ETH"
           },
           "created_at":"2017-10-01T16:50:51Z",
           "resource":"account",
        }],
    }
    

    编辑

    Json反序列化程序:

    public class JsonNetDeseralizer : IDeserializer
    {
        private readonly JsonSerializerSettings settings;
    
        public string RootElement { get; set; }
        public string Namespace { get; set; }
        public string DateFormat { get; set; }
    
        public JsonNetDeseralizer(JsonSerializerSettings settings)
        {
            this.settings = settings;
        }
    
        public T Deserialize<T>(IRestResponse response)
        {
            return JsonConvert.DeserializeObject<T>(response.Content, settings);
        }
    }
    

    0 回复  |  直到 6 年前