owlike/genson

How to use type parameter for deserialize?

Closed this issue · 2 comments

http://genson.io/Documentation/UserGuide/#generic-types says

genson.deserialize(..., new GenericType<List<Integer>>(){})

is used for deserializing generic list.

Now I have the following code and the concrete type is passed as a parameter:

import com.owlike.genson.GenericType;
import com.owlike.genson.Genson;

import java.util.LinkedList;
import java.util.List;

public class Program {

	private static final Genson genson = new Genson();

	public static void main(String[] args) {
		Store s = new Store(1, "Target");
		List<Store> l = new LinkedList<Store>();
		l.add(s);

		String json = genson.serialize(l);

		System.out.println(json);

		List<Store> l2 = loadList(json, Store.class);

		Store s2= l2.get(0);
	}

	private static <T> List<T> loadList(String json, Class<T> clazz) {
		return genson.deserialize(json, new GenericType<>() {};);
	}
}

class Store {

	private int id;
	private String name;

	public Store(int id, String name) {
		this.id = id;
		this.name = name;
	}

	public Store() {
	}

	public int getId() {
		return id;
	}

	public String getName() {
		return name;
	}


	public void setId(int id) {
		this.id = id;
	}

	public void setName(String name) {
		this.name = name;
	}
}

It throws exception saying "class java.util.HashMap cannot be cast to class Store".

Note if I write List<Store> l2 = genson.deserialize(json, new GenericType<List<Store>>() {}) instead of using loadList, the program runs without issues.

How does Genson support type parameter? How do I revise the loadList function?

Github issues is not the right place to ask there questions. Please use the mailing list for this, here.

The problem is more with how you use your code. You could update it to take the generic type and pass to it new GenericType<List<Store>>() {}. Currently it's not working because you supply no type information to Genson (note how you do nothing with the input class).

I invented the following workaround.

public static <T> List<T> deserializeList(Genson genson, String json, Class<T> type) {
	Object o = genson.deserialize(json, Object.class);
	List l = (List) o;
	List<T> l2 = new LinkedList<>();
	for (int i = 0; i < l.size(); i++) {
		String j = genson.serialize(l.get(i));
		l2.add(genson.deserialize(j, type));
	}

	return l2;
}

For a list type, I have to deserialize it to Object, then for each list item, do a second ser de.