来自不寻常的JSON的Parseto对象

时间:2014-03-11 15:17:26

标签: asp.net-mvc json asp.net-mvc-4

我有一个像这样的JSON文件:

{
    "date": "2012-01-05",
    "rate": {
        "GBP": "5.2549",
        "BGN": "2.2189",
        "JPY": "0.043985",
        "AUD": "3.4648",
        "EGP": "0.5601",
        "SEK": "0.4898",
        "BRL": "1.8444",
        "RSD": "0.0412",
        "EUR": "4.3398",
        "CAD": "3.3165",
        "USD": "3.3796",
        "HUF": "0.013449",
        "MXN": "0.2459",
        "MDL": "0.2867",
        "NOK": "0.5646",
        "CZK": "0.1672",
        "KRW": "0.002925",
        "RUB": "0.1057",
        "PLN": "0.9596",
        "CNY": "0.5363",
        "NZD": "2.6406",
        "UAH": "0.4194",
        "XDR": "5.1605",
        "TRY": "1.7911",
        "DKK": "0.5837",
        "INR": "0.0638",
        "CHF": "3.5629",
        "XAU": "175.2918",
        "AED": "0.9201",
        "ZAR": "0.4114"
    }
}

我需要将rate中的值作为模型列表(List<Model>

public class Model
{
    public string Currency {get; set;}
    public double Value {get; set;}

}

谢谢!

1 个答案:

答案 0 :(得分:0)

可以分2步完成。

步骤1:

将json字符串反序列化为类:

public class RootObject
{
    public string date { get; set; }
    public Dictionary<string, double> rate { get; set; }
}

使用以下熟悉的代码:

string json = "YOUR_JSON";
RootObject root = JsonConvert.DeserializeObject<RootObject>(json);

步骤-2:

现在,您可以使用以下LINQ提取词典作为Model的列表:

List<Model> models = root.rate.Select(x => new Model {Currency = x.Key, Value = x.Value}).ToList();