Mario
Mario

Reputation: 14790

How can I read JSON in ASP.NET?

I need a simple method to read the results from Amazon Affiliates URL, I have the code for Amazon and I get a JSON result which I cannot read in ASP.NET. Is there an easy method to parse the JSON data in ASP.NET 4.5 ?

Upvotes: 1

Views: 12739

Answers (3)

Aviran Cohen
Aviran Cohen

Reputation: 5691

Use JSON.NET package, its great and simple.

To install the package:

Open the console. "View" > "Other Windows" > "Package Manager Console"

Then type the following: Install-Package Newtonsoft.Json

You can both read the Json object as dynamic object or as strongly-typed one. In case you want to read the Json type as a strongly typed object, you can do the following:

The class to populate the data:

public class AmazonAffiliate
{

public string Username {get;set;}

public string Email {get;set;}

public Date BirthDate {get;set;}

}

Method for converting Json strings to strongly-typed class:

    public static T GetJsonContent<T>(string jsonAsString)
    {
        var serializer = new JsonSerializer<T>();
        return serializer.DeserializeFromString(jsonAsString);
    }

And you can use it like this:

AmazonAffiliate affiliate = GetJsonContent<AmazonAffiliate>(jsonString);

Upvotes: 1

Joey Gennari
Joey Gennari

Reputation: 2361

You could also use the .NET built-in JavaScriptSerializer:

using System.Web.Script.Serialization;
...
JavaScriptSerializer js = new JavaScriptSerializer();
dynamic obj = js.Deserialize<dynamic>(jsonString);

Upvotes: 5

Aghilas Yakoub
Aghilas Yakoub

Reputation: 28990

You can use JObject class based on Json.net

Link : http://james.newtonking.com/pages/json-net.aspx

For parsing you can use JObject.Parse Method

Code

   var jsonString = @"{""Name"":""Aghilas"",""Company"":""....."",
                        ""Entered"":""2012-03-16T00:03:33.245-10:00""}";

    dynamic json = JValue.Parse(jsonString);

    // values require casting
    string name = json.Name;
    string company = json.Company;
    DateTime entered = json.Entered;

Upvotes: 2

Related Questions