2012-02-28 70 views
2

我正在寫一個helloworld MonoTouch應用程序來使用ServiceStack消費Json,並有一個兩部分相關的問題。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中添加Rates集合到我的DTO中?

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

回答

7

ServiceStack有一個真棒流利的JSON解析器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"), 
    }) 
}); 
+0

嘿Anuj,再次感謝。我想我現在欠你一杯咖啡......下一次你在溫哥華.... :) – 2012-02-28 20:53:09

+4

我對MonoTouch企業應用程序服務層的估計只是下降了一半我覺得....哇,ServiceStack有一個不錯的客戶框架。 – 2012-02-28 20:54:28