从代码隐藏文件创建JSon数组

时间:2012-01-26 12:12:59

标签: asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-2 asp.net-ajax

如何使用asp.net,c#创建如下所示的arraylist。我可以使用JsonTextWriter创建这样的数组,但不想在我的解决方案中添加任何其他dll。

  [{ "id": "slide-img-1", "client": "nature beauty", "desc": "nature beauty photography" },
  { "id": "slide-img-2", "client": "nature beauty", "desc": "add your description here" },
  { "id": "slide-img-3", "client": "nature beauty", "desc": "add your description here" },
  { "id": "slide-img-4", "client": "nature beauty", "desc": "add your description here" },
  { "id": "slide-img-5", "client": "nature beauty", "desc": "add your description here" },
  { "id": "slide-img-6", "client": "nature beauty", "desc": "add your description here" },
  { "id": "slide-img-7", "client": "nature beauty", "desc": "add your description here"}];

谢谢,

与Ashish

2 个答案:

答案 0 :(得分:4)

您可以使用a JavaScriptSerializer

假设数组中的实体类似于:

public class Entity 
{
  public string id { get; set; }
  public string client { get; set; }
  public string desc {get; set; }

  [ScriptIgnore]
  public string PropertyThatIsIgnored { get;set; }
}

然后就可以这样使用了:

Entity[] entities = ...;
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(entities);

或者,如果需要更复杂的序列化,您可以考虑使用a DataContractJsonSerializer,因为它允许more extensibility when serializing / deserializing

答案 1 :(得分:2)

使用.NET framework附带的JavaScriptSerializer类。

看看here

var js = new JavaScriptSerializer();
string myJson = js.Serialize(new string[] {"A", "B", "C"});