我有以下数据结构:

Class UserModel {
Long pkid;
String name;
public UserModel() {
this.pkid = new Long(1001);
this.name = "ABC";
}
}


现在,我已将其转换为json:

UserModel usrObj = new UserModel();
Gson gson = new Gson();
String json = gson.toJson(userObj);


所以我的json字符串现在就像:

{  "pkid": 1001,
    "name": "ABC" }


但是我需要创建json作为

{"com.vlee.ejb.UserModel": [
{  "pkid": 1001,
    "name": "ABC" } ] }


我可以轻松地创建一个json,例如:

{"userModel": [
{  "pkid": 1001,
        "name": "ABC" } ] }


当我面临使用点创建索引的问题时。

我不确定如何添加密钥"com.vlee.ejb.UserModel"

最佳答案

    UserModel userObj = new UserModel();
    HashMap map = new HashMap();
    ArrayList array = new ArrayList();
    array.add(userObj);
    map.put(userObj.getClass().getName(), array);
    Gson gson = new Gson();
    String json = gson.toJson(map);
    System.out.println(json);


它输出:
{“ com.vlee.ejb.UserModel”:[{“ pkid”:1001,“ name”:“ ABC”}]}

10-07 19:48