给一个 JSONObject.toJavaObject() 的例子
时间: 2024-03-22 15:13:29 浏览: 62
假设有一个 JSON 字符串如下:
```
{
"name": "Alice",
"age": 25,
"isMarried": false,
"hobbies": ["reading", "travelling"]
}
```
我们可以使用 JSONObject.parseObject() 方法将其转换为 JSONObject 对象,然后使用 JSONObject.toJavaObject() 方法将其转换为 Java 对象,如下所示:
```
import com.alibaba.fastjson.JSONObject;
public class JsonToJavaExample {
public static void main(String[] args) {
String jsonString = "{\"name\":\"Alice\",\"age\":25,\"isMarried\":false,\"hobbies\":[\"reading\",\"travelling\"]}";
JSONObject jsonObject = JSONObject.parseObject(jsonString);
Person person = jsonObject.toJavaObject(Person.class);
System.out.println(person.getName());
System.out.println(person.getAge());
System.out.println(person.isMarried());
System.out.println(person.getHobbies()[0]);
System.out.println(person.getHobbies()[1]);
}
}
class Person {
private String name;
private int age;
private boolean isMarried;
private String[] hobbies;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isMarried() {
return isMarried;
}
public void setMarried(boolean married) {
isMarried = married;
}
public String[] getHobbies() {
return hobbies;
}
public void setHobbies(String[] hobbies) {
this.hobbies = hobbies;
}
}
```
输出结果如下:
```
Alice
25
false
reading
travelling
```
可以看到,我们成功将 JSON 字符串转换为了 Java 对象。
阅读全文