简体   繁体   English

使用org.json包将JSON对象转换为Java bean

[英]Convert JSON object to Java bean using org.json package

I have Java bean class, for example: 我有Java bean类,例如:

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

I can convert it easily to org.json object using 我可以轻松地将其转换为org.json对象

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? 是否可以将JSONObject转换为Java bean类?

There's an existing library that implements the reflection method to convert JSON Object to Java bean, called Gson . 现有一个实现反射方法以将JSON对象转换为Java bean的库,称为Gson

Using it you can convert JSON text (the result of calling jo.toString() in your code) back to the User type: 使用它,您可以将JSON文本(在代码中调用jo.toString()的结果)转换回User类型:

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. 该库还实现了toJson()方法,因此对于所有情况,您应该有可能用Gson替换对json.org实现的使用。

There is no built-in way to do that using the json.org library. 没有使用json.org库的内置方法。

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. 为每个bean编写一个fromJSONObject()方法,该方法使用JSONObject#has()JSONObject#get*()来获取所需的值并处理任何类型问题。
  2. Write a global method which uses JSONObject#names() and reflection to populate a bean instance with data from a JSONObject. 编写一个全局方法,该方法使用JSONObject#names()和反射来用JSONObject中的数据填充bean实例。 This is not difficult, but could be too heavy lifting if all you need it to use it with a couple of bean classes. 这并不困难,但是如果您需要将其与几个Bean类一起使用,则可能会很繁重。
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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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