【问题标题】:Convert json object to java object. Unknown class将 json 对象转换为 java 对象。未知类
【发布时间】: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文件吗?

标签: java json generics gson


【解决方案1】:

您可以使用 Gson 谷歌库将 json 对象转换为 Java 类运行时。 Gson 库有一个方法 fromJson(String,className)。它接受 2 个参数第一个字符串,其中包含 json 数据和您要转换的第二个类名称,最后它返回 Java 类对象

【讨论】:

    【解决方案2】:

    试试这个:

    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);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-29
      • 2012-05-29
      • 1970-01-01
      • 2023-03-03
      • 2023-03-17
      • 1970-01-01
      相关资源
      最近更新 更多