Friday, February 12, 2016

1.0 Iterate JSON Object in Apache Velocity

Well this is slightly json implementation (ex: gson, jettison, json) dependent solution. 

For example :
     
  • jsonObject.entrySet()  //  returns Set<Entry<String, JsonElement>> for gson 
  •  jsonObject.keys()         // returns Iterator<String>   for jettison
 So we are gonna write a Custom apache velocity Uberspector exploiting the above facts.
  1. Create a class MyUberspector which extends SecureUberspector 
import java.util.Iterator;
import org.apache.velocity.util.introspection.Info;
import org.apache.velocity.util.introspection.SecureUberspector;
import com.google.gson.JsonObject;

public class MyUberspector extends SecureUberspector {

    @Override
    public Iterator getIterator(Object object, Info info) throws Exception {
        if (object instanceof JsonObject) {
            return new VelJSONObjectIerator((JsonObject) object);
        } else {
            return super.getIterator(object, info);
        }
    }
}


 2. Create a class VelJSONObjectIerator which implements Iterator<Object>

import java.nio.channels.UnsupportedAddressTypeException;
import java.util.Iterator;
import java.util.Map.Entry;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

public class VelJSONObjectIerator implements Iterator<Object> {
    private Iterator<Entry<String, JsonElement>> iterator;

    public VelJSONObjectIerator(JsonObject object) {
        this.iterator = object.entrySet().iterator();
    }

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

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

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


3. Set property "runtime.introspector.uberspect" to class name of MyUberspector class.


Thats it ..!!! 

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

Velocity template :
 #foreach ($x in $jsonObject)
   $x.key | $x.value
#end


Output:

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




For  jsonObject.keys() solution, look for blog 1.1
          

 

2 comments:


  1. I followed this blog but my json variable was not accepted as valid json object and I was not able to iterate through it.
    any help will be appreciated, thanks advance

    ReplyDelete
    Replies
    1. you have to set json variable in velocity context while initializing velocity engine

      Delete