Having problems deserializing json in C #
I have an example of what I am trying to deserialize below and I am getting a bunch of different errors when I try to pull the data. All I want is to output the id value, but I cannot figure it out.
{"object":"payments","entry":[{"id":"546787862118679","time":1417135022,"changed_fields":["actions"]}]}
public class Entry
{
public string id { get; set; }
public int time { get; set; }
public List<string> changed_fields { get; set; }
}
public class RootObject
{
public string @object { get; set; }
public List<Entry> entry { get; set; }
}
dynamic result = new StreamReader(request.InputStream).ReadToEnd();
var items = JsonConvert.DeserializeObject<RootObject>(result);
string paymentID = items.entry.FirstorDefault().id;
Returns this error:
'System.Collections.Generic.List' does not contain a definition for 'FirstOrDefault ()'
source to share
With a quick glance at the error I received, it appears at this line:
string paymentID = items.entry.FirstorDefault().id; //should be .FirstOrDefault().id;
... to enumerate through each element Entry
in items.entry
, which is List<Entry>
:
if (items.entry != null && items.entry.Count > 0)
{
foreach(Entry entryItem in items.entry)
{
if (!string.IsNullOrEmpty(entryItem.id))
{
string paymentID = entryItem.id;
}
}
}
... to access the first element Entry
:
if (items.entry != null && items.entry.Count > 0)
{
if (!string.IsNullOrEmpty(items.entry[0].id))
{
string paymentID = items.entry[0].id;
}
}
source to share
I have a feeling this will work if your code is:
string paymentID = items.entry.FirstorDefault().id;
were
string paymentID = items.entry.FirstorDefault().id;
And what's your mistake really
'System.Collections.Generic.List' does not contain a definition for 'FirstorDefault'
How Collections.Generic.List contains a definition for FirstOrDefault
( System.Linq
)
source to share
Why are you loading the result into a dynamic type? Use a string.
void Main()
{
string json = @"{""object"":""payments"",""entry"":[{""id"":""546787862118679"",""time"":1417135022,""changed_fields"":[""actions""]}]}";
Root root = JsonConvert.DeserializeObject<Root>(json);
Entry entry = root.Entry.FirstOrDefault();
}
public class Entry
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("time")]
public int Time { get; set; }
[JsonProperty("changed_fields")]
public string[] ChangedFields { get; set; }
}
public class Root
{
[JsonProperty("object")]
public string Object { get; set; }
[JsonProperty("entry")]
public Entry[] Entry { get; set; }
}
source to share
For some reason (I still don't know why) your code works when you change the result type from dynamic to string.
string result = new StreamReader(request.InputStream).ReadToEnd();
if (!string.IsNullOrWhiteSpace(result)) {
var items = JsonConvert.DeserializeObject<RootObject>(result);
string paymentID = items.entry.FirstorDefault().id;
}
source to share