如何在ASP.net中创建JSON数组?

时间:2015-07-01 12:40:45

标签: c# asp.net json

我在PHP中创建了以下格式 JSON数组。但现在我想使用C#代码在 ASP.net 中创建相同格式的JSON数组。我该如何创建呢?

{
  "android": [
    {
      "name": "aaa",
      "version": "123"
    },
    {
      "name": "bb",
      "version": "34"
    },
    {
      "name": "cc",
      "version": "56"
    }
  ]
}

正在使用以下方法

  Public Class OutputJson
  {
  public List<Entity> Android { get; set; }
  }
  Public Class Entity
  {
  Public string Name { get; set; }
  Public string Version { get; set; }
  }
  outputJson = new OutputJson{
  Android = new List<Entity> 
 {
    new Entity { Name = "aaa", Version = "123"},
    new Entity { Name = "bb", Version = "34"},
    new Entity { Name = "cc", Version = "56"},
}   
var output = new  System.Web.Script.Serialization.JavaScriptSerializer().Serialize(outputJson); 

string YourJsonArray = output; 
Response.Clear(); 
Response.ContentType = "application/json; charset=utf-8"; 
Response.Write(YourJsonArray );
Response.End();

我收到以下错误

Runtime Error
Description: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.

Details: To enable the details of this specific error message to be viewable on remote machines, please create a <customErrors> tag within a "web.config" configuration file located in the root directory of the current web application. This <customErrors> tag should then have its "mode" attribute set to "Off".

我该如何解决?

3 个答案:

答案 0 :(得分:6)

最简单的方法是将json库添加到项目中。例如,使用NuGet:

<!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="css/main.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css"> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> </head> <body> <i class="fa fa-paper-plane"></i> <p>test?</p> </body> </html>

然后,序列化您的数据:

Install-Package Newtonsoft.Json

这应该在你的例子中产生文字输出。

答案 1 :(得分:2)

您可以使用.NET framework附带的JavaScriptSerializer Class

命名空间: System.Web.Script.Serialization

假设您的Outputjson类似于:

Public Class OutputJson
{
    public List<Entity> Android { get; set; }
}

实体就像:

Public Class Entity
{
    Public string Name { get; set; }
    Public string Version { get; set; }
}

因此JavaScriptSerializer类的使用将是这样的:

var outputJson = new OutputJson{
    Android = new List<Entity> 
    {
        new Entity { Name = "aaa", Version = "123"},
        new Entity { Name = "bb", Version = "34"},
        new Entity { Name = "cc", Version = "56"},
    }   
var output = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(outputJson); 

答案 2 :(得分:1)

试试这个

 var s = new JavaScriptSerializer();
 string jsonClient = s.Serialize(customers);