Create json using JavaScriptSerializer

2019-08-30 07:02发布

问题:

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

Applied on the Class 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;
   }
}

which gives me output as:

{"Data":[[["Trigonometry","Chemistry"]],[["Physics","Biology"]]]}

But I want it in following format:

{"Data":[["Trigonometry","Chemistry"],["Physics","Biology"]]}

How JavaScriptSerializer works?
Why is it creating another array?
What should I do to fix this?

回答1:

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

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.