public string toJSON(SqlDataReader o)
{
StringBuilder s = new StringBuilder();
s.Append("[");
if (o.HasRows)
while (o.Read())
s.Append("{" + '"' + "Id" + '"' + ":" + o["Id"] + ", "
+ '"' + "CN" + '"' + ":" + o["CatName"] + ", "
+ '"' + "Ord" + '"' + ":" + o["Ord"] + ","
+ '"' + "Icon" + '"' + ":" + o["Icon"] + "}, ");
s.Remove(s.Length - 2, 2);
s.Append("]");
o.Close();
return s.ToString();
}
Run Code Online (Sandbox Code Playgroud)
我在这里使用我自己的函数进行序列化.我需要知道这是一个好方法还是我应该使用另一个.顺便说一下,我试过使用JavaScriptSerializer但是这不适用于SqlDataReader.感谢名单
我使用asp.net和Web表单.在我的项目中,我有asmx web服务
[WebMethod]
public string GetSomething()
{
// avoid circual reference(parent child)
List<RetUsers> res = repo.GetAllUser().Select(c => new RetUsers {User_ID = c.User_ID,User_Name = c.User_Name,Date_Expire = c.Date_Expire }).ToList();
string res1 = res.ToJson();
// extension methods
return res.ToJson();
}
Run Code Online (Sandbox Code Playgroud)
结果就是这种格式.
[
{"User_ID":1,"User_Name":"Test 1","Date_Expire":null},
{"User_ID":2,"User_Name":"Test 2","Date_Expire":null}
]
Run Code Online (Sandbox Code Playgroud)
如何在$ .ajax sucess中附加标记此结果以获得此输出:
1 - 测试1,2 - 测试2.
我有一个观点,我想转换成JSON.我可以使用什么SQL在服务器上生成需要返回的JSON字符串?
试着在这里学习一些jquery/js和一些ajax.我创建了一个简单的asp.net Web表单项目,其中包含以下内容:
namespace JSONTest
{
public partial class _Default : System.Web.UI.Page
{
public class Contact
{
public string Name { get; set; }
}
List<Contact> contacts = new List<Contact>
{
new Contact{ Name = "George" },
new Contact{ Name = "Mike" },
new Contact{ Name = "Steve"}
};
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Contact> GetContacts()
{
return contacts;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的js文件就是这样的:
$(document).ready(function () {
$.ajax({
type: "POST",
async: true,
url: "Default.aspx/GetContacts",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: …Run Code Online (Sandbox Code Playgroud)