使用JSON和Serializer返回MULTIPLE列表

时间:2015-06-28 09:14:58

标签: javascript c# asp.net json webmethod

我正在使用以下命令从我的ASP.NET WebMethod向我的Javascript发送一个List:

List<Person> plist = new List<Person>();

string json = "";
System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
json = oSerializer.Serialize(plist );

return json;

我正在使用它从我的JS中检索这些值:

function onSuccess(val) {
        var obj = JSON.parse(val)
        obj.forEach(function (entry) {
               console.log(entry);
       });
}

一切都运作良好。但是现在我想返回MULTIPLE列表,例如:

List<Person> plist = new List<Person>();
List<Car> carlist = new List<Car>();
List<Car> jeeplist = new List<Car>();

使用我之前使用的相同机制。如何将两个列表插入到Serializer中并从我的JS中打印出来?

修改

如何从JS中获取值?是这样的吗?

obj.forEach(function (entry) {
         entry.forEach(function (act)
         {
               console.log(act);
         })
});

1 个答案:

答案 0 :(得分:6)

struct TwoLists
{
    public List<Person> plist;
    public List<Car> carlist;
}

...

TwoLists lists;
lists.plist = new List<Person>();
lists.carlist = new List<Car>();
...
string json = "";
System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
json = oSerializer.Serialize(lists);

return json;

...

function onSuccess(val) {
    var obj = JSON.parse(val);
    obj.plist.forEach(function (entry) {
        console.log(entry);
    });
    obj.carlist.forEach(function (entry) {
        console.log(entry);
    });
}