我有以下数据结构:
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" } ] }
当我在使用点创建索引时遇到问题。
我不确定如何添加 key "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"}]}
关于android - 如何在json数据中添加索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15777525/