I have a method that returns an IEnumberable containing 1..n records. How do I convert the results to a JSON string?
Thanks!
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);
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;
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;
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With