对象转jsonobject,java
时间: 2023-12-06 19:38:48 浏览: 80
java对象转JSON
5星 · 资源好评率100%
以下是Java中对象转JSONObject的示例代码:
```java
// 导入相关包
import com.alibaba.fastjson.JSONObject;
// 定义一个Java对象
public class Student {
private int id;
private String username;
private String studentNo;
// 构造函数
public Student(int id, String username, String studentNo) {
this.id = id;
this.username = username;
this.studentNo = studentNo;
}
// getter和setter方法
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getStudentNo() {
return studentNo;
}
public void setStudentNo(String studentNo) {
this.studentNo = studentNo;
}
}
// 将Java对象转为JSONObject
Student student = new Student(12, "super先生", "20231232520");
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(student);
System.out.println(jsonObject);
```
输出结果为:
```
{"id":12,"studentNo":"20231232520","username":"super先生"}
```
相关问题:
阅读全文