Question

I'm very new to JSON, and I need to parse some that an API is providing. A quick google search turned up JSON.NET, so I'm trying to use it now to parse this JSON into a list object. First of all, is JSON.NET the best library to use for this?

This is what I'm trying to do: I have a class called Item, for example. The json has many "elements" (if that's what they are called), and each contains 3 fields: an integer named id, a string named name, and a datetime named creationTime. I would like to parse all of these Item "elements" from the json into a list of Item objects. I have created 3 fields in the Item class to match the JSON. How can this be done using JSON.NET?

I've tried:

List<Item> fav = (List<Item>)new JsonSerializer().Deserialize(new JsonReader((TextReader)new StreamReader(response.GetResponseStream())));

but it doesn't seem to work. I get a casting error - it just can't process it into a list enclosure, but I'm not even sure whether it's able to process the JSON into one Item class (JSON.NET is not very well-documented, but I'm going to heavily debug it tomorrow).

Can you give me some sample code to explain how I can parse it with JSON.NET?

Thanks!

UPDATE: By the way, forgot to mention - my project is going to be targeting .NET Framework 2.0, so I'm using the legacy version of JSON.NET: 1.3.1. Are there any HUGE advantages that may make the project worth converting to .NET 3.5, while undermining the minimal system requirements?

UPDATE #2: I have decided to use the JavascriptSerializer class in System.Web.Extensions.dll instead of JSON.NET, and a question about that is posted here. Thanks!

Was it helpful?

Solution

I would recomend that you upgrade to .net framework 3.5 and use ASP.Net MVC to build your json services. See:

http://msmvps.com/blogs/omar/archive/2008/10/03/create-rest-api-using-asp-net-mvc-that-speaks-both-json-and-plain-xml.aspx

OTHER TIPS

I realise this question is about 3 years old, but I thought I'd just add that if you want to build a JSON based Api, NancyFx is awesome: http://nancyfx.org/

EDIT: An example as requested, really easy. To get started just add the nancyfx asp package to a web project via NuGet. (if you're adding it to an existing app on a sub path, you'll need to add a location to the web.config, otherwise you're good to go)

using Nancy;
using Nancy.ModelBinding;

public class Api : NancyModule
        {
            public Api()
            {
                Get["/api/order/create"] = x => 
                { 
                    var order = this.Bind<Order>(); //xml/json negotiated based on content header

                    var result = ... // Do stuff here

                    return Response.AsJson(result); 
                };
            }       
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top