简体   繁体   中英

Convert json object to java object. Unknown class

I want to use a JSONObject (net.sf.json) stored as a string in a database, and set and get attributes from this JSONObject. I want to get java objects stored in this JSONObjects (of unknown class at compile time). How can I do this?

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

This gives error: com.google.gson.internal.LinkedTreeMap cannot be cast to User

I've also tried with:

public static <T> T getAttribute(String key, JSONObject json, Class<T> type)
{
    return new Gson().fromJson(json.toString(), type);
}

Any tips?

You can use Gson google library for converting json object into Java class runtime. Gson library has a method fromJson(String,className). Its take 2 argument first String which contains json data and second class Name you want to convert and finally its return Java class Object

Try this:

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

I am not sure but this should also work - JSONObject jsonObject = new JSONObject(user); , and not jsonObject.put("user", user);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM