Sunday, February 14, 2016

1.1 Iterate JSON Object in Apache Velocity

..in continuation with 1.0.

 If the jsonObject provides key() method. There is a slight modification in VelJSONObjectIerator method (step2 of Blog 1.0).


import java.nio.channels.UnsupportedAddressTypeException;
import java.util.Iterator;
import org.codehaus.jettison.json.JSONObject;

public class VelJSONObjectIerator implements Iterator<Object> {

    private final JSONObject jsonObject;

    private Iterator<String> iterator;

    public VelJSONObjectIerator(JSONObject jsonObject) {
        this.jsonObject = jsonObject;
        iterator = jsonObject.keys();
    }

    public boolean hasNext() {
        return iterator.hasNext();
    }

    public Object next() {
        return iterator.next();
    }

    public void remove() {
        throw new UnsupportedAddressTypeException();
    }
}


 for jsonObject = {"1":"un","2":"deux","3":"trois","4":"quatre"} 

Velocity template : 

 
#foreach ($key in $jsonObject)
   $key | $jsonObject.get($key)
#end


Output:

   1 | "un"
   2 | "deux"
   3 | "trois"
   4 | "quatre"






No comments:

Post a Comment