Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert an IEnumerable to JSON?

Tags:

json

c#

.net-4.0

I have a method that returns an IEnumberable containing 1..n records. How do I convert the results to a JSON string?

Thanks!

like image 936
DenaliHardtail Avatar asked Apr 29 '11 04:04

DenaliHardtail


4 Answers

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);

Which produces the output

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

And then you can get your sequence back

IEnumerable<Foo> foos = serializer.Deserialize<IEnumerable<Foo>>(outputOfFoos);
like image 137
Anthony Pegram Avatar answered Nov 05 '22 14:11

Anthony Pegram


Maybe you can try this:

var categories = from c in db.tableone
                 select new { key = c.tableoneID, value = c.tableoneName };

JsonResult categoryJson = new JsonResult();
categoryJson.Data = categories;

return categoryJson;
like image 40
Notepad Avatar answered Nov 05 '22 15:11

Notepad


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;
    }
}
like image 3
Harsh Baid Avatar answered Nov 05 '22 16:11

Harsh Baid


When using MVC you can use the "System.Web.Helpers.Json class". I needed a few items rendered with the page in json:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Categorie { get; set; }
}

In the view:

@{
          var products = new List<Product> { 
                new Product{ Id = 1, Name = "test product", Categorie = 1},
                new Product{ Id = 2, Name = "another product",Categorie = 1},
                new Product{ Id = 3, Name = "more stuff",Categorie = 1},
                new Product{ Id = 4, Name = "even more",Categorie = 2},
                new Product{ Id = 5, Name = "and the last",Categorie = 2}
            };
        }

    //fill the javascript variable with products
    var products= @(Html.Raw(Json.Encode(products) )); 

Note the Html.Raw...

While this can be helpfull, don't over use it. Rendering large sections of data into your page makes the page large and may cause performance issues when the browser can not cache your results. If you need more data, use a REST call, so the browser can cache the results.

like image 3
Nicow Avatar answered Nov 05 '22 14:11

Nicow