Converting a POJO to Map

11,922

Solution 1

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;
}

Solution 2

First create json from object

Gson gson = new GsonBuilder().create();
String json = gson.toJson(obj);// obj is your object 

Then create map using json

Map<String,Object> result = new Gson().fromJson(json, Map.class);

Resource Link:

  1. Create JSONObject from POJO
  2. How can I convert JSON to a HashMap using Gson?
Share:
11,922
Muli Yulzary
Author by

Muli Yulzary

I am an energetic, social and ambitious software engineer. By night - backseat gamer (CS 1.3-1.6, CSGO, DOTA2).

Updated on June 15, 2022

Comments

  • Muli Yulzary
    Muli Yulzary about 2 years

    I have the following:

    public class ChargeRequest {
        @Expose
        private String customerName;
        @Expose
        private String stripeToken;
        @Expose
        private String plan;
        @Expose
        private String[] products;
    
        gettersAndSetters()...
    
        public Map<String, Object> toMap() {
            return gson.fromJson(this, new TypeToken<Map<String, Object>>() {
            }.getType());
        }
    
        public String toString() {
            return gson.toJson(this, getClass());
        }
    }
    

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

    My adapter:

    public static class JsonAdapter implements  JsonDeserializer<ChargeRequest>{
            @Override
            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.

    Code:

    ObjectMapper om = new ObjectMapper();
    Map<String, Object> req = om.convertValue(request, Map.class);
    
  • Muli Yulzary
    Muli Yulzary over 7 years
    Obviously that does not work... "The JsonDeserializer MapTypeAdapter failed to deserialize json object {"customerName":"a","plan":"sample-plan-1","products":["samp‌​le-awesome-product"]‌​} given the type interface java.util.Map"
  • SkyWalker
    SkyWalker over 7 years
    Make sure the white space is cleaned up around your JSON string before sending it to Gson. stackoverflow.com/a/5426895/2293534 @MuliYulzary
  • Muli Yulzary
    Muli Yulzary over 7 years
    There are no whitespaces.
  • SkyWalker
    SkyWalker over 7 years
    On that case you can follow the tutorial for creating json from object : mkyong.com/java/jackson-2-convert-java-object-to-from-json
  • gurpal2000
    gurpal2000 almost 5 years
    Upvoted as this doesn't require any intermediate conversion to json and keeps the types as present in the Object.