JSON-deserialization in .NET
If you're working with ASP.NET MVC (an excellent framework), passing JSON-data from your views to your Controllers is a magic experience - the JSON-objects are
Data Contract:
{
[DataMember]
public string Headline { get; set; }
[DataMember]
public string Url { get; set; }
}
{ Headline: 'Spree', Abstract: 'Häftiga Spree', Url: 'http://www.spree.se/', Lars: false },
{ Headline: 'Synaptic', Abstract: 'Trygga Synaptic', Url: 'http://www.synaptic.se/', Lars: true },
{ Headline: '.NETAkademien', Abstract: 'Ett nätverk av .NET-specialister', Url: 'http://www.netakademien.se/', Lars: false }
]";
automatically serialized to their .NET representations, as long as you have the
same field/property names.
same field/property names.
However, if you want to parse data outside of the magical web world - say you'd like to parse JSON-data from your Windows Phone application - you're out of luck. Unless ...
To parse JSON-data, I initially tried the DataContractJsonSerializer, since I prefer using the plain/native Microsoft .NET framework whenever possible. I quickly ran into issues though, finding that it simply did not work for my purposes. After som web scurrying, I found Newtonsoft's Json-parser and fell in love:
Data Contract:
[DataContract]
public class LinkItem{
[DataMember]
public string Headline { get; set; }
[DataMember]
public string Abstract { get; set; }[DataMember]
public string Url { get; set; }
}
JSON-data:
var jsonData = @"[ { Headline: 'Spree', Abstract: 'Häftiga Spree', Url: 'http://www.spree.se/', Lars: false },
{ Headline: 'Synaptic', Abstract: 'Trygga Synaptic', Url: 'http://www.synaptic.se/', Lars: true },
{ Headline: '.NETAkademien', Abstract: 'Ett nätverk av .NET-specialister', Url: 'http://www.netakademien.se/', Lars: false }
]";
Parsing:
IEnumerable<LinkItem> items = JsonConvert.DeserializeObject<IEnumerable<LinkItem>>(jsonData);
The parsing works even though I've defined data in JSON (the Lars property)
that I am not interested in.
that I am not interested in.
Comments