RSS

Returning JSON object from an ASP.NET page

01 Jul

images

I think that the web service is a good solution to do that, but what If do you be enforced to deal with JSON through ASP .NET.

You have a class “Product” as following, and you have an object “o” represents the class:

public class Product
{
public int ID { get; set; }
public string Name { get; set; }
public int Price { get; set; }
}

If you want to write Response.Write(x), you will get “namespace.Product”, and this is totally wrong. In brief, to do that you have to execute the following script in your code-behind page:

var o = new System.Web.Script.Serialization.JavaScriptSerializer();
System.Text.StringBuilder x = new System.Text.StringBuilder();
o.Serialize(new Product { ID = 1, Name = “Product abc”, Price = 1000 }, x);
Response.ContentType = “application/json”;
Response.Write(x);

You will get the following result: {“ID”:1,”Name”:”Note 2″,”Price”:1000}

 
Leave a comment

Posted by on July 1, 2014 in ASP .NET

 

Tags: , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: