Problems copying JArray to ObservableCollection

So, I feel like I'm really close, just not enough glue to make the magic work.

Consider the code class:

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;

      

and this JSON response from App.MobileService.InvokeApiAsync

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

      

I have verified that the returned JArray is parsed and populated correctly. I want to get data in ObservableCollection.

I've tried various spells of this, with the simplest being:

items = result;

      

what mistakes with

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

      

or

items = new ObservableCollection<Transaction> (result);

      

what errors with:

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

      

I've read loads of samples that make it look like it should be super easy, so I'm sure I'm missing something simple. Any help was appreciated.

UPDATE:

This does what I want and works, but I seem to be defeating the purpose of some of the built-in deserialization functions of JSON.NET classes:

            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);
            }

      

+3


source to share


1 answer


If you already have JArray

in result

, and you want to convert it to ObservableCollection<Transaction>

, you can do it like this:

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

      



Demo : https://dotnetfiddle.net/saQmas

+4


source







All Articles