2011-04-29 39 views

回答

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

它產生輸出

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

然後你就可以得到您的序列回

IEnumerable<Foo> foos = serializer.Deserialize<IEnumerable<Foo>>(outputOfFoos); 
2

你可以做這樣的使用.NET Framework本身和不使用任何第三方工具

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; 
    } 
} 
+0

這是接受答案的複本。 – mbomb007 2015-11-11 18:02:53

5

也許你可以試試這個:

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

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

return categoryJson; 
2

當使用MVC,你可以使用"System.Web.Helpers.Json class"。我需要在JSON與頁面呈現的幾個項目:

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

在視圖:

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

注意Html.Raw ...

雖然這可能是有益的,對吧不要過度使用它。將大量數據呈現到頁面中會使頁面變大,並且在瀏覽器無法緩存結果時可能會導致性能問題。如果您需要更多數據,請使用REST調用,以便瀏覽器可以緩存結果。