0

I have Java bean class, for example:

public class User  implements Serializable{
    protected String Name        = null;
    protected String Password    = null;
    // ...
}  

I can convert it easily to org.json object using

User u = new User();
u.setName("AAA");
u.setPassword("123");
JSONObject jo = new JSONObject(u);

Is it way to convert JSONObject to Java bean class?

1
  • 1
    No, Java isn't Python, you can't create classes on runtime Commented Oct 5, 2014 at 15:57

3 Answers 3

10

There's an existing library that implements the reflection method to convert JSON Object to Java bean, called Gson.

Using it you can convert JSON text (the result of calling jo.toString() in your code) back to the User type:

User user = new Gson().fromJson(jSONObjectAsString, User.class);

This library also implements a toJson() method, so it should be possible for you to replace your use of the json.org implementation with Gson for all cases.

Sign up to request clarification or add additional context in comments.

Comments

1

There is no built-in way to do that using the json.org library.

Depending on your needs, you can either

  1. write a fromJSONObject() method for each of your beans, which uses JSONObject#has() and JSONObject#get*() to get the needed values and handle any type problems.
  2. Write a global method which uses JSONObject#names() and reflection to populate a bean instance with data from a JSONObject. This is not difficult, but could be too heavy lifting if all you need it to use it with a couple of bean classes.

Comments

1
public static Object toBean(JSONObject jobject, Object object) {
    for (Field field : object.getClass.getDeclaredFields()) {
        field.set(object, jobject.getString(field.getName()));
    }
}

Call:

User user = (User) toBean(jo, new User());

2 Comments

Do you mean object.getClass().getDeclaredFields() ? Forgot the return statement.
add this statement field.setAccessible(true);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.