All Downloads are FREE. Search and download functionalities are using the official Maven repository.

aQute.lib.json.ArrayHandler Maven / Gradle / Ivy

Go to download

A command line utility and Ant plugin to wrap, build, or examine bundles.

There is a newer version: 2.4.0
Show newest version
package aQute.lib.json;

import java.io.*;
import java.lang.reflect.*;
import java.util.*;

import aQute.lib.hex.*;

public class ArrayHandler extends Handler {
	Type	componentType;

	ArrayHandler(@SuppressWarnings("unused") Class< ? > rawClass, Type componentType) {
		this.componentType = componentType;
	}

	@Override
	void encode(Encoder app, Object object, Map visited) throws IOException, Exception {
		
		// Byte arrays should not be treated as arrays. We treat them
		// as hex strings
		
		if ( object instanceof byte[]) {
			StringHandler.string(app,  Hex.toHexString((byte[]) object));
			return;
		}
		app.append("[");
		app.indent();
		String del = "";
		int l = Array.getLength(object);
		for (int i = 0; i < l; i++) {
			app.append(del);
			app.encode(Array.get(object, i), componentType, visited);
			del = ",";
		}
		app.undent();
		app.append("]");
	}

	@Override
	Object decodeArray(Decoder r) throws Exception {
		ArrayList list = new ArrayList();
		r.codec.parseArray(list, componentType, r);
		Object array = Array.newInstance(r.codec.getRawClass(componentType), list.size());
		int n = 0;
		for (Object o : list)
			Array.set(array, n++, o);

		return array;
	}
}