我想使用存储在数据库中作为字符串的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);
}
有什么提示吗?
您可以使用 Gson Google 库将 json 对象转换为 Java 类运行时。Gson 库有一个来自 Json(String,className) 的方法。它首先需要 2 个参数字符串,其中包含 json 数据和您要转换的第二个类名称,最后返回 Java 类对象
试试这个:
public static void main(String[] args){
User user = new User();
Gson gson = new Gson();
String json = gson.toJson(user);
User u = getAttribute(json);
}
public static <T> T getAttribute(String json, Class<T> type){
return new Gson().fromJson(json, type);
}
我不确定,但这应该也有效 - JSONObject jsonObject = new JSONObject(user);
,而不是jsonObject.put("user", user);