RSS

How to convert an IEnumerable to JSON

25 Jan

.Net Framework Logo

You can do it like this using .NET Framework itself and without using any 3rd party tools

using System.Web.Script.Serialization;

public class Json
{
    public string getJson()
    {
       // some code //
       var products = // IEnumerable object //
       string json = new JavaScriptSerializer().Serialize(products);
       // some code //
       return json;
    }
}

Serializing Usage:

IEnumerable<int> sequenceOfInts = new int[] { 1, 2, 3 };
IEnumerable<Foo> sequenceOfFoos = new Foo[] { new Foo() { Bar = "A" }, new Foo() { Bar = "B" } };

var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string outputOfInts = serializer.Serialize(sequenceOfInts);
string outputOfFoos = serializer.Serialize(sequenceOfFoos);

Output:

[1,2,3]
[{"Bar":"A"},{"Bar":"B"}]

Deserializing Usage:

IEnumerable<int> sequenceOfInts = serializer.Deserialize<IEnumerable<int>>(outputOfInts);
IEnumerable<Foo> sequenceOfFoos = serializer.Deserialize<IEnumerable<Foo>>(outputOfFoos);

Reference links: StackOverflow.com

 
1 Comment

Posted by on January 25, 2012 in .NET, ASP.NET, C#, JavaScript

 

Tags: , , , , , , , ,

One response to “How to convert an IEnumerable to JSON

Leave a comment