我正在编写一个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...
答案 0 :(得分:7)
ServiceStack有一个非常棒的Fluent JSON Parser API,可以很容易地对现有模型起作用,而无需使用“契约”基本序列化。这应该让你开始:
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"),
})
});