使用JavaScriptSerializer创建json [英] Create json using JavaScriptSerializer
本文介绍了使用JavaScriptSerializer创建json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Asp.net的通用处理程序中有以下代码:
I have following code in Generic Handler of Asp.net:
var students= Student.GetStudents();
var result = new
{
Data = students.Select(s => new []{s.subjects})
};
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var json = serializer.Serialize(result);
context.Response.ContentType = "application/json";
context.Response.Write(json);
应用于类Student
:
public class Student
{
public List<String> subjects{get; set;}
Student()
{
subjects= new List<string>();
}
public static IEnumerable<Student> GetStudents()
{
List<Student> students= new List<Student>();
Student s1 = new Student();
s1.subjects.Add("Trigonometry");
s1.subjects.Add("Chemistry");
students.Add(row1);
Student s2 = new Student();
s2.subjects.Add("Physics");
s2.subjects.Add("Biology");
students.Add(s2);
return students;
}
}
这给我输出为:
{"Data":[[["Trigonometry","Chemistry"]],[["Physics","Biology"]]]}
但是我想要以下格式:
{"Data":[["Trigonometry","Chemistry"],["Physics","Biology"]]}
JavaScriptSerializer如何工作?
为什么要创建另一个数组?
我该怎么做才能解决此问题?
How JavaScriptSerializer works?
Why is it creating another array?
What should I do to fix this?
推荐答案
它并不完美,但对我有用:
Its not perfect but working for me:
var rows = Row.GetRows();
StringBuilder sb = new StringBuilder("\"aaData\":[");
for (int i = 0; i < rows.Count; i++)
{
if (i == 0){ sb.Append("["); }
else { sb.Append(",["); }
for (int j = 0; j < rows[i].fields.Count; j++)
{
if (j == 0){
sb.Append("\"" + rows[i].fields[j].ToString() + "\"");
}
else{
sb.Append(",\"" + rows[i].fields[j].ToString() + "\"");
}
}
sb.Append("]");
}
sb.Append("]}");
var json = sb.ToString();
context.Response.ContentType = "application/json";
context.Response.Write(json);
由于JavaScriptSerializer
向json对象添加了一个[]
,因此我尝试不使用它并手动创建json字符串.
Since the JavaScriptSerializer
adding one more []
to the json object, I tried not to use it and create the json string manually.
让我知道使用这种方式的利弊.
Let me know the pros and cons of using this way.
这篇关于使用JavaScriptSerializer创建json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文