从C#生成json的最佳方法是什么?

时间:2022-09-13 04:02:05

i am trying to mimic an example where they are using hard coded JSON

我试图模仿他们使用硬编码JSON的例子

{
"page": 1,
"total": 1,
"records": 2,
"rows": [
   {"id": 1, "cell": ["1", "Super Item", "300", 0, null, false, false]},
       {"id": 2, "cell": ["2", "Item 1", "100", 1, 1, false, false]},
       {"id": 3, "cell": ["3", "Sub Item 1", "50", 2, 2, true, true]},
       {"id": 4, "cell": ["4", "Sub Item 2", "25", 2, 2, false, false]},
       {"id": 5, "cell": ["5", "Sub-sub Item 1", "25", 3, 4, true, true]},
       {"id": 6, "cell": ["6", "Sub Item 3", "25", 2, 2, true, true]},
       {"id": 7, "cell": ["7", "Item 2", "200", 1, 1, false, false]},
       {"id": 8, "cell": ["8", "Sub Item 1", "100", 2, 7, false, false]},
       {"id": 9, "cell": ["9", "Sub-sub Item 1", "50", 3, 8, true, true]},
       {"id": 10, "cell": ["10", "Sub-sub Item 2", "50", 3, 8, true, true]},
       {"id": 11, "cell": ["11", "Sub Item 2", "100", 2, 7, true, true]}
    ]
} 

but i need to generate this from C#. Are there any suggestions for the best way to go about generating this above in C#?

但我需要从C#生成这个。有没有关于在C#中生成以上内容的最佳方法的建议?

4 个解决方案

#1


11  

The Controller class has a Json method that serialises objects as JSON, so in your action method you just create the object and call the method:

Controller类有一个Json方法,它将对象序列化为JSON,所以在你的action方法中你只需要创建对象并调用方法:

public ActionResult GetData() {
  return Json(
    new {
      page = 1,
      total = 1,
      records = 2,
      rows = new[] {
        new { id = 1, cell = new object[] { "1", "Super Item", "300", 0, null, false, false } },
        new { id = 2, cell = new object[] { "2", "Item 1", "100", 1, 1, false, false } },
        new { id = 3, cell = new object[] { "3", "Sub Item 1", "50", 2, 2, true, true } },
        new { id = 4, cell = new object[] { "4", "Sub Item 2", "25", 2, 2, false, false } },
        new { id = 5, cell = new object[] { "5", "Sub-sub Item 1", "25", 3, 4, true, true } },
        new { id = 6, cell = new object[] { "6", "Sub Item 3", "25", 2, 2, true, true } },
        new { id = 7, cell = new object[] { "7", "Item 2", "200", 1, 1, false, false } },
        new { id = 8, cell = new object[] { "8", "Sub Item 1", "100", 2, 7, false, false } },
        new { id = 9, cell = new object[] { "9", "Sub-sub Item 1", "50", 3, 8, true, true } },
        new { id = 10, cell = new object[] { "10", "Sub-sub Item 2", "50", 3, 8, true, true } },
        new { id = 11, cell = new object[] { "11", "Sub Item 2", "100", 2, 7, true, true } }
      }
    } 
  );
}

#2


4  

There's a class built into .Net 2+ which is called 'JavaScriptSerializer' which creates a JSON structured string based on a .Net typed class.

有一个内置于.Net 2+中的类,称为“JavaScriptSerializer”,它基于.Net类型类创建一个JSON结构化字符串。

Using the serializer you can simply created a class with properties and collections to represent your JSON data. Create an instance of it in .Net server side code and then respond using the serializer to generate a valid JSON string response.

使用序列化程序,您只需创建一个包含属性和集合的类来表示您的JSON数据。在.Net服务器端代码中创建它的实例,然后使用序列化程序响应以生成有效的JSON字符串响应。

Here's an example of converting a Person class instance to a serialized JSON string;

这是将Person类实例转换为序列化JSON字符串的示例;

JavaScriptSerializer js = new JavaScriptSerializer();
Person p1 = new Person();
p1.firstName = "Brian";
p1.lastName = "Scott";
p1.department = "Microsoft";
p1.address.addressline1 = "Microsoft";
p1.address.addressline2 = "";
p1.address.city = "Redmond";
p1.address.state = "Seattle";
p1.address.country = "America";
p1.address.pin = 560028;
p1.technologies = new string[] { "IIS", "ASP.NET", "JavaScript", "AJAX" };

string strJSON = js.Serialize(p1);

This will produce a valid JSON string of

这将生成一个有效的JSON字符串

{"firstName":"Brian","lastName":"Scott","department":"Microsoft","address":{"addressline1":"Microsoft","addressline2":"","city":"Redmond","state":"Seattle","country":"America","pin":560028},"technologies":["IIS","ASP.NET","JavaScript","AJAX"]}

If you are intending to use a webservice to produce the JSON response to the client side then you can mark your method as;

如果您打算使用Web服务向客户端生成JSON响应,那么您可以将方法标记为;

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetPersonJSON()
{
    JavaScriptSerializer js = new JavaScriptSerializer();
    Person p1 = new Person();
p1.firstName = "Brian";
p1.lastName = "Scott";
p1.department = "Microsoft";
p1.address.addressline1 = "Microsoft";
p1.address.addressline2 = "";
p1.address.city = "Redmond";
p1.address.state = "Seattle";
p1.address.country = "America";
p1.address.pin = 560028;
p1.technologies = new string[] { "IIS", "ASP.NET", "JavaScript", "AJAX" };

return js.Serialize(p1);
}

#3


1  

Apparently you are trying to populate a jqGrid and you're using ASP.NET MVC. If you have defined a class for these values:

显然你正在尝试填充jqGrid而你正在使用ASP.NET MVC。如果您为这些值定义了一个类:

["1", "Super Item", "300", 0, null, false, false]

You can store all the elements in a collection myCollection
you can do something like this:

您可以将所有元素存储在集合myCollection中,您可以执行以下操作:

var ReturnData = new
    {
        total = totalPages,
        page = page,
        records = totalRecords,
        rows = myCollection.Select(r => new
        {
            id = r.Id.ToString(),
            cell = new String[] { r.Field1, r.Field2, r.Field3, r.Field4 }
        })
        };

return (Json(ReturnData, JsonRequestBehavior.DenyGet));

#4


0  

class Row {
   public int id {get;set;}
   public object[] cell {get;set;}
}

class Data {
  public int page {get;set;}
  public int total {get;set;}
  public int records {get;set;}
  public Row[] rows {get;set;}
}

var myData = new Data(){ .... };
var json =  new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(myData);

#1


11  

The Controller class has a Json method that serialises objects as JSON, so in your action method you just create the object and call the method:

Controller类有一个Json方法,它将对象序列化为JSON,所以在你的action方法中你只需要创建对象并调用方法:

public ActionResult GetData() {
  return Json(
    new {
      page = 1,
      total = 1,
      records = 2,
      rows = new[] {
        new { id = 1, cell = new object[] { "1", "Super Item", "300", 0, null, false, false } },
        new { id = 2, cell = new object[] { "2", "Item 1", "100", 1, 1, false, false } },
        new { id = 3, cell = new object[] { "3", "Sub Item 1", "50", 2, 2, true, true } },
        new { id = 4, cell = new object[] { "4", "Sub Item 2", "25", 2, 2, false, false } },
        new { id = 5, cell = new object[] { "5", "Sub-sub Item 1", "25", 3, 4, true, true } },
        new { id = 6, cell = new object[] { "6", "Sub Item 3", "25", 2, 2, true, true } },
        new { id = 7, cell = new object[] { "7", "Item 2", "200", 1, 1, false, false } },
        new { id = 8, cell = new object[] { "8", "Sub Item 1", "100", 2, 7, false, false } },
        new { id = 9, cell = new object[] { "9", "Sub-sub Item 1", "50", 3, 8, true, true } },
        new { id = 10, cell = new object[] { "10", "Sub-sub Item 2", "50", 3, 8, true, true } },
        new { id = 11, cell = new object[] { "11", "Sub Item 2", "100", 2, 7, true, true } }
      }
    } 
  );
}

#2


4  

There's a class built into .Net 2+ which is called 'JavaScriptSerializer' which creates a JSON structured string based on a .Net typed class.

有一个内置于.Net 2+中的类,称为“JavaScriptSerializer”,它基于.Net类型类创建一个JSON结构化字符串。

Using the serializer you can simply created a class with properties and collections to represent your JSON data. Create an instance of it in .Net server side code and then respond using the serializer to generate a valid JSON string response.

使用序列化程序,您只需创建一个包含属性和集合的类来表示您的JSON数据。在.Net服务器端代码中创建它的实例,然后使用序列化程序响应以生成有效的JSON字符串响应。

Here's an example of converting a Person class instance to a serialized JSON string;

这是将Person类实例转换为序列化JSON字符串的示例;

JavaScriptSerializer js = new JavaScriptSerializer();
Person p1 = new Person();
p1.firstName = "Brian";
p1.lastName = "Scott";
p1.department = "Microsoft";
p1.address.addressline1 = "Microsoft";
p1.address.addressline2 = "";
p1.address.city = "Redmond";
p1.address.state = "Seattle";
p1.address.country = "America";
p1.address.pin = 560028;
p1.technologies = new string[] { "IIS", "ASP.NET", "JavaScript", "AJAX" };

string strJSON = js.Serialize(p1);

This will produce a valid JSON string of

这将生成一个有效的JSON字符串

{"firstName":"Brian","lastName":"Scott","department":"Microsoft","address":{"addressline1":"Microsoft","addressline2":"","city":"Redmond","state":"Seattle","country":"America","pin":560028},"technologies":["IIS","ASP.NET","JavaScript","AJAX"]}

If you are intending to use a webservice to produce the JSON response to the client side then you can mark your method as;

如果您打算使用Web服务向客户端生成JSON响应,那么您可以将方法标记为;

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetPersonJSON()
{
    JavaScriptSerializer js = new JavaScriptSerializer();
    Person p1 = new Person();
p1.firstName = "Brian";
p1.lastName = "Scott";
p1.department = "Microsoft";
p1.address.addressline1 = "Microsoft";
p1.address.addressline2 = "";
p1.address.city = "Redmond";
p1.address.state = "Seattle";
p1.address.country = "America";
p1.address.pin = 560028;
p1.technologies = new string[] { "IIS", "ASP.NET", "JavaScript", "AJAX" };

return js.Serialize(p1);
}

#3


1  

Apparently you are trying to populate a jqGrid and you're using ASP.NET MVC. If you have defined a class for these values:

显然你正在尝试填充jqGrid而你正在使用ASP.NET MVC。如果您为这些值定义了一个类:

["1", "Super Item", "300", 0, null, false, false]

You can store all the elements in a collection myCollection
you can do something like this:

您可以将所有元素存储在集合myCollection中,您可以执行以下操作:

var ReturnData = new
    {
        total = totalPages,
        page = page,
        records = totalRecords,
        rows = myCollection.Select(r => new
        {
            id = r.Id.ToString(),
            cell = new String[] { r.Field1, r.Field2, r.Field3, r.Field4 }
        })
        };

return (Json(ReturnData, JsonRequestBehavior.DenyGet));

#4


0  

class Row {
   public int id {get;set;}
   public object[] cell {get;set;}
}

class Data {
  public int page {get;set;}
  public int total {get;set;}
  public int records {get;set;}
  public Row[] rows {get;set;}
}

var myData = new Data(){ .... };
var json =  new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(myData);