使用 org.json 包将 JSON 对象转换为 Java bean
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26204323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert JSON object to Java bean using org.json package
提问by Costa Mirkin
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 类?
采纳答案by Guss
There is no built-in way to do that using the json.org library.
使用 json.org 库没有内置的方法来做到这一点。
Depending on your needs, you can either
根据您的需要,您可以
- write a
fromJSONObject()
method for each of your beans, which usesJSONObject#has()
andJSONObject#get*()
to get the needed values and handle any type problems. - 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.
fromJSONObject()
为每个 bean编写一个方法,该方法使用JSONObject#has()
和JSONObject#get*()
获取所需的值并处理任何类型问题。- 编写一个全局方法,该方法使用
JSONObject#names()
反射来使用来自 JSONObject 的数据填充 bean 实例。这并不难,但如果你需要它与几个 bean 类一起使用它可能会太繁重。
回答by Pracede
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 实现的使用。
回答by DuanLX
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());