将POJO转换为Map

Mul*_*ary 4 java json gson stripe-payments

我有以下内容:

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

我正试图转换ChargeRequest成一个Map<String, Object>与Gson.

我的适配器:

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;
        }
}
Run Code Online (Sandbox Code Playgroud)

我得到了:Type information is unavailable, and the target is not a primitive对于字符串数组.怎么了?

最后更新:我终于决定回到杰克逊,一切都按预期工作.

码:

ObjectMapper om = new ObjectMapper();
Map<String, Object> req = om.convertValue(request, Map.class);
Run Code Online (Sandbox Code Playgroud)

yuk*_*uan 6

发布简单版本:

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;
}
Run Code Online (Sandbox Code Playgroud)


Sky*_*ker 5

首先从对象创建json

Gson gson = new GsonBuilder().create();
String json = gson.toJson(obj);// obj is your object 
Run Code Online (Sandbox Code Playgroud)

然后使用json创建地图

Map<String,Object> result = new Gson().fromJson(json, Map.class);
Run Code Online (Sandbox Code Playgroud)

资源链接:

  1. 从POJO创建JSONObject
  2. 如何使用Gson将JSON转换为HashMap?