java 对象转JSONObject
时间: 2024-01-26 17:11:07 浏览: 81
可以使用阿里巴巴的 fastjson 库将 Java 对象转换为 JSONObject,使用方式如下:
```java
import com.alibaba.fastjson.JSONObject;
public class ObjectToJsonExample {
public static void main(String[] args) {
// 创建 Java 对象
Person person = new Person("张三", 18, "男");
// 将 Java 对象转换为 JSONObject
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(person);
// 打印 JSONObject
System.out.println(jsonObject);
}
}
// 定义一个 Person 类
class Person {
private String name;
private int age;
private String gender;
public Person(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
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 String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
```
输出结果:
```
{"age":18,"gender":"男","name":"张三"}
```
阅读全文