【发布时间】:2015-01-23 13:35:26
【问题描述】:
我想使用作为字符串存储在数据库中的 JSONObject (net.sf.json),并从该 JSONObject 设置和获取属性。我想获取存储在此 JSONObjects 中的 java 对象(在编译时属于未知类)。我该怎么做?
// Let's say I have a POJO "User" with getters and setters
public static void main(String[] args)
{
User user = new User();
JSONObject jsonObject = new JSONObject();
jsonObject.put("user", user);
User u = getAttribute("user", jsonObject);
}
public static <T> T getAttribute(String key, JSONObject json)
{
Type typeOfT = new TypeToken<T>(){}.getType();
return new Gson().fromJson(json.toString(), typeOfT);
}
这会产生错误:com.google.gson.internal.LinkedTreeMap 无法转换为用户
我也试过:
public static <T> T getAttribute(String key, JSONObject json, Class<T> type)
{
return new Gson().fromJson(json.toString(), type);
}
有什么建议吗?
【问题讨论】:
-
可以显示json文件吗?