迭代JSON中的复杂对象列表?

时间:2010-12-09 23:22:53

标签: javascript jquery json iteration

我构建了一个要放入JSON结果的对象列表:

Person personA = new Person("nameA", "age");
Person personB = new Person("nameB", "age");
Person personC = new Person("nameC", "age");

List<Car> cars = new ArrayList<Car>();

cars.add(new Car("Blue", "Small", personA));
cars.add(new Car("Green", "Big", personB));
cars.add(new Car("Red", "Big", personC));

在我的JSON结果图中,我把:

result.put("cars", cars);

如何在JavaScript中迭代此集合。我需要访问对象的“深层”元素。

$.getJSON(window.actionName,{
            someId: someId}, function (ans){

  //I want something like this
  foreach(car in ans.cars){
      car.person.age
  }
});

编辑:

result map private Map<String,List<Car>> result = 
        new HashMap<String, List<Car>>();

    result.put("cars", cars);

但它似乎没有将此列表发送给客户端。我在Chrome调试器中收到此错误:

ReferenceError: value is not defined
... failed to load resource: the server responded with a status of 500 (Internal Server Error)

答案:错误是因为我正在序列化具有hibernante注释的对象。我创建了Bean对象并对它们进行了序列化,现在是序列化(并且迭代正在运行)

2 个答案:

答案 0 :(得分:2)

//...

  for(var i = 0, car; car = ans.cars[i]; ++i){
      alert(car.person.age);
  }

答案 1 :(得分:1)

有功能风格:

ans.cars.forEach(function(car) {
  // do something with ‘car’
});

这是标准的ECMAScript 5.正如你标记了这个“jquery”,如果你不想依赖于Array.forEach那么你可能想尝试jQuery版本:

$.each(ans.cars, function(index, car) {
  // do something with ‘car’
});