Вопрос

I am writing a helloworld MonoTouch App to use ServiceStack to consume Json and have a two part related question.

My test json is: https://raw.github.com/currencybot/open-exchange-rates/master/latest.json

In my DTO object how to I use different named properties that map to json elements?

I have this, and it works, but I want to use different field names?

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

And how do I add the Rates collection in my DTO from this json?

"rates": {
    "AED": 3.6731,
    "AFN": 48.330002,
    "ALL": 103.809998,
     ETC...
Это было полезно?

Решение

ServiceStack has an awesome Fluent JSON Parser API that makes it really easy to work against your existing model without having to use the "Contract" base serialization. This should get you started:

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"),
    })
});
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top