无法将JArray复制到ObservableCollection

时间:2014-08-31 20:48:34

标签: json.net observablecollection

所以我觉得自己非常接近,只是缺少一些胶水才能让魔法发挥作用。

考虑一个代码类:

public class Transaction
{
    [JsonProperty(PropertyName = "date")]
    public DateTime Date { get;  set; }

    [JsonProperty(PropertyName = "payee")]
    public string Payee { get;  set; }

    [JsonProperty(PropertyName = "amount")]
    public double Amount { get;  set; }

    [JsonProperty(PropertyName = "category")]
    public string Category { get;  set; }
}

private ObservableCollection<Transaction> items;
private JArray result;

来自App.MobileService.InvokeApiAsync的这个JSON响应

[
    {
        "date": "2014-09-26T00:00:00Z",
        "payee": "Expensive Restaurant",
        "amount": -199,
        "category": "Dining",
    }
]

我已验证返回的JArray对象是否已正确解析并填充。我想将数据导入ObservableCollection。

我尝试了各种各样的咒语,最简单的是:

items = result;

错误

Cannot implicitly convert type 'Newtonsoft.Json.Linq.JArray' to 'System.Collections.ObjectModel.ObservableCollection<Transaction>'

或:

items = new ObservableCollection<Transaction> (result);

错误:

Argument 1: cannot convert from 'Newtonsoft.Json.Linq.JArray' to 'System.Collections.Generic.IEnumerable<Transaction>'

我已经阅读了大量的样本,看起来这应该是非常容易的,所以我确定我错过了一些简单的东西。任何帮助表示赞赏。

更新:

这就是我想要和工作的东西,但似乎我正在挫败JSON.NET类的一些内置反序列化功能的目的:

            foreach (JObject jObject in result)
            {
                Transaction trans = new Transaction();
                trans.Date = (DateTime)jObject["date"];
                trans.Payee = (string)jObject["payee"];
                trans.Amount = (double)jObject["amount"];
                trans.Category = (string)jObject["category"];
                items.Add(trans);
            }

1 个答案:

答案 0 :(得分:4)

如果JArray中已有result,并且您希望将其转换为ObservableCollection<Transaction>,则可以这样做:

items = result.ToObject<ObservableCollection<Transaction>>();

演示https://dotnetfiddle.net/saQmas