简体   繁体   中英

iterate over list of complex objects in JSON?

I build a list of objects to put into a JSON result:

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

and in my JSON result map, I put:

result.put("cars", cars);

How to iterate over this collection in JavaScript. I need to have access in object's "deep" elements.

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

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

EDIT:

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

    result.put("cars", cars);

but it seemes that this lists aren't sent to the client. I get this error in Chrome debugger:

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

ANSWER: Error was because I was serializing objects that had hibernante annotations. I created Bean objects that and serialized them and now the serialization (and iteration is working)

//...

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

There's the functional style:

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

This is standard ECMAScript 5. As you've tagged this “jquery”, you may want to try the jQuery version instead if you don't want to rely on Array.forEach to be there:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM