Muli Yulzary Muli Yulzary - 1 year ago 217
Java Question

Converting a POJO to Map **RESOLVED**

I have the following:

public class ChargeRequest {
private String customerName;
private String stripeToken;
private String plan;
private String[] products;


public Map<String, Object> toMap() {
return gson.fromJson(this, new TypeToken<Map<String, Object>>() {

public String toString() {
return gson.toJson(this, getClass());

I'm trying to convert
into a
Map<String, Object>
with Gson.

My adapter:

public static class JsonAdapter implements JsonDeserializer<ChargeRequest>{
public ChargeRequest deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
ChargeRequest cr = new ChargeRequest();
JsonObject o = json.getAsJsonObject();
o.add("customerName", o.get("customerName"));
o.add("stripeToken", o.get("stripeToken"));
o.add("plan", o.get("plan"));
JsonArray jProds = o.get("products").getAsJsonArray();
cr.products = new String[jProds.size()];
for (int i = 0; i < jProds.size(); i++) {
cr.products[i] = jProds.get(i).getAsString();
return cr;

I'm getting:
Type information is unavailable, and the target is not a primitive
for the array of strings. what's wrong?

Final update: I've finally decided to move back to Jackson and everything works as expected.


ObjectMapper om = new ObjectMapper();
Map<String, Object> req = om.convertValue(request, Map.class);

Answer Source

Post a simple version:

public final static Map<String, Object> pojo2Map(Object obj) {
    Map<String, Object> hashMap = new HashMap<String, Object>();
    try {
        Class<? extends Object> c = obj.getClass();
        Method m[] = c.getMethods();
        for (int i = 0; i < m.length; i++) {
            if (m[i].getName().indexOf("get") == 0) {
                String name = m[i].getName().toLowerCase().substring(3, 4) + m[i].getName().substring(4);
                hashMap.put(name, m[i].invoke(obj, new Object[0]));
    } catch (Throwable e) {
        //log error
    return hashMap;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download