如何将JAVA数组转换成 JSON对象或JSON字符串

自定义对象

public class CourseQuery implements Serializable {

    private static final long serialVersionUID = -4699713095477151086L;

    private String courseId;// 课程编号
    private String courseName;// 课程名称
    private String courseTeacher;// 课程任课老师姓名
    private String courseDate;// 课程上课时间
    private String courseIntroduction;// 课程介绍

    public CourseQuery(String courseId, String courseName, String courseTeacher, String courseDate,
            String courseIntroduction) {
        super();
        this.courseId = courseId;
        this.courseName = courseName;
        this.courseTeacher = courseTeacher;
        this.courseDate = courseDate;
        this.courseIntroduction = courseIntroduction;
    }

    public String getCourseId() {
        return courseId;
    }

    public void setCourseId(String courseId) {
        this.courseId = courseId;
    }

    public String getCourseName() {
        return courseName;
    }

    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }

    public String getCourseTeacher() {
        return courseTeacher;
    }

    public void setCourseTeacher(String courseTeacher) {
        this.courseTeacher = courseTeacher;
    }

    public String getCourseDate() {
        return courseDate;
    }

    public void setCourseDate(String courseDate) {
        this.courseDate = courseDate;
    }

    public String getCourseIntroduction() {
        return courseIntroduction;
    }

    public void setCourseIntroduction(String courseIntroduction) {
        this.courseIntroduction = courseIntroduction;
    }

    @Override
    public String toString() {
        return "{courseId:" + courseId + ", courseName:" + courseName + ", courseTeacher:" + courseTeacher
                + ", courseDate:" + courseDate + ", courseIntroduction:" + courseIntroduction + "}";
    }

}

比如将一个上述对象的数组装换成一个JSON对象或JSON字符串

形如:

{
"data":
[
{...},{....},{...}
}
}

2个回答

你是在用Spring写吗? 是的话mavn添加依赖包,然后@ResponseBody注解返回消息会自动转成json的,

com.fasterxml.jackson.core
jackson-databind
2.8.10

用JSON的jar包啊,JSON.toJSONString(obj)把你的对象替换那个obj,json的jar包很多阿里的fast的。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐