2

我正在编写一个 helloworld MonoTouch 应用程序来使用 ServiceStack 来使用 Json 并有一个两部分相关的问题。

我的测试 json 是:https ://raw.github.com/currencybot/open-exchange-rates/master/latest.json

在我的 DTO 对象中,如何使用映射到 json 元素的不同命名属性?

我有这个,它可以工作,但我想使用不同的字段名称?

public class Currency
{
    public string disclaimer { get; set; }
    public string license { get; set; }
    public string timestamp  { get; set; }
}

以及如何从这个 json 在我的 DTO 中添加 Rates 集合?

"rates": {
    "AED": 3.6731,
    "AFN": 48.330002,
    "ALL": 103.809998,
     ETC...
4

1 回答 1

7

ServiceStack 有一个很棒的 Fluent JSON Parser API,它可以很容易地处理现有模型,而无需使用“Contract”基本序列化。这应该让你开始:

public class Rates {
    public double AED { get; set; }
    public double AFN { get; set; }
    public double ALL { get; set; }
}

public class Currency {
    public string disclaimer { get; set; }
    public string license { get; set; }
    public string timestamp  { get; set; }
    public Rates CurrencyRates { get; set; }
}

...

var currency = new Currency();
currency.CurrencyRates = JsonObject.Parse(json).ConvertTo(x => new Currency{
    disclaimer   = x.Get("disclaimer"),
    license = x.Get("license"),
    timestamp = x.Get("timestamp"),
    CurrencyRates = x.Object("rates").ConvertTo(r => new Rates {
        AED = x.Get<double>("AED"),
        AFN = x.Get<double>("AFN"),
        ALL = x.Get<double>("ALL"),
    })
});
于 2012-02-28T20:49:00.670 回答