Rakesh Garg
Rakesh Garg

Reputation: 27

Iterate JSONArray in Velocity Template

I am trying to iterate JSONArray in velocity template but its not working I found velocity template can iterate collection, array,hash-map objects Anyone can help me to iterate JSONArray

Thanks in Advance

Upvotes: 1

Views: 3579

Answers (1)

Will Glass
Will Glass

Reputation: 4850

You can do this with a custom uberspector. This lets you customize how Velocity interprets gets/sets/iterators.

I did the exact same thing recently for jsonlib. Here's my uberspector.

package util;

import java.util.Iterator;

import net.sf.json.JSONArray;

import org.apache.velocity.util.introspection.Info;
import org.apache.velocity.util.introspection.SecureUberspector;

/**
 * Customized Velocity introspector.  Used so that FML can iterate through JSON arrays.
 */
public class CustomUberspector extends SecureUberspector
{
    @Override
    @SuppressWarnings("rawtypes")
    public Iterator getIterator(Object obj, Info i) throws Exception
    {
        if (obj instanceof JSONArray)
        {
            return new JsonArrayIterator((JSONArray) obj);
        }
        else
        {
            return super.getIterator(obj, i);
        }
    }
}

JsonArrayIterator is just a simple iterator through the array. if you are using a different JSON library, just customize this class.

package util;

import java.util.Iterator;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;

public class JsonArrayIterator implements Iterator<Object>
{
    private final JSONArray array;
    private int nextIndex;
    private final int length;

    public JsonArrayIterator(JSONArray array)
    {
        this.array = array;
        nextIndex = 0;
        length = array.size();
    }

    @Override
    public boolean hasNext()
    {
        return nextIndex < length;
    }

    @Override
    public Object next()
    {
        nextIndex++;
        try
        {
            return array.get(nextIndex - 1);
        }
        catch (JSONException e)
        {
            throw new IllegalStateException(e);
        }
    }

    @Override
    public void remove()
    {
        throw new UnsupportedOperationException();
    }


}

The final step is to specify the uberspector in your velocity properties.

runtime.introspector.uberspect=util.CustomUberspector

Upvotes: 1

Related Questions