【问题标题】:using JSON response from REST api with nonstandard names使用来自具有非标准名称的 REST api 的 JSON 响应
【发布时间】:2014-12-03 06:15:49
【问题描述】:
{"balances-and-info":{"on_hold":[],"available":    {"USD":0.93033384},"usd_volume":"243.18","fee_bracket":    {"maker":"0.00","taker":"0.60"},"global_usd_volume":"0.09942900"}}

我有这个 JSON 响应,我试图将它存储在一个对象中,但是正如您所见,“balances-and-info”不能用作变量名。我一直使用的方法是:

RestClient client = new RestClient("http://currency-api.appspot.com/api/");
RestRequest request = new RestRequest(url);

var response = client.Execute<Currency>(request);

Currency obj = response.Data;

显然课程要容易得多

public class Currency
{
    public string rate { get; set; }
}

那么我该如何处理呢?

【问题讨论】:

    标签: c# json rest restsharp


    【解决方案1】:

    String.replace() balances-and-info 与 balances_and_info

    在您的代码中

    YourObject deserialized = parseResponse(obj.replace("balances-and-info", "balances_and_info"));
    

    YourObject parseResponse(string response) {
        try
        {
            // https://www.nuget.org/packages/Newtonsoft.Json/ 
            // Json.NET
            YourObject ret = JsonConvert.DeserializeObject<YourObject>(response);
            return ret;
        }
        catch (JsonSerializationException)
        {
            // do something 
        }
        return null;
    }
    

    你的对象

    使用http://json2csharp.com/ 并生成您的对象(复制响应字符串,将 balances-and-info 替换为 balances_and_info 并生成)

    public class Available
    {
        public double USD { get; set; }
    }
    
    public class FeeBracket
    {
        public string maker { get; set; }
        public string taker { get; set; }
    }
    
    public class BalancesAndInfo
    {
        public List<object> on_hold { get; set; }
        public Available available { get; set; }
        public string usd_volume { get; set; }
        public FeeBracket fee_bracket { get; set; }
        public string global_usd_volume { get; set; }
    }
    
    public class YourObject
    {
        public BalancesAndInfo balances_and_info { get; set; }
    }
    

    【讨论】:

    • 不是逐字逐句正确,但你指出了我正确的方向。得到它的工作 - 谢谢!
    • 我很高兴它有帮助,仍然代码遗漏来自凌晨 2 点直接进入浏览器的编码 :)
    猜你喜欢
    • 2021-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-17
    • 2015-07-29
    • 2019-01-02
    • 1970-01-01
    相关资源
    最近更新 更多