0

我在 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 是如何工作的?
为什么要创建另一个数组?
我应该怎么做才能解决这个问题?

4

1 回答 1

0

它并不完美,但对我有用:

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);

由于向json对象JavaScriptSerializer添加了一个[],我尝试不使用它并手动创建json字符串。

让我知道使用这种方式的利弊。

于 2012-10-17T05:18:33.773 回答