Java JSON 之 数组 转 JSON 字符串

http://www.verejava.com/?id=16998590966648

下载依赖 jar 包   

json.jar 


package com.json8;

import org.json.JSONArray;
import org.json.JSONException;

public class Test
{
	public static void main(String[] args)
	{
		/*
		 题目: 将颜色数组 红色,绿色,蓝色 转成 JSON 字符串
		 */
		String[] colors={"红色","蓝色","绿色"};
		
		// JSONArray 存入 colors 
		try
		{
			JSONArray jsonArray=new JSONArray(colors);
			System.out.println(jsonArray.toString());
		} catch (JSONException e)
		{
			e.printStackTrace();
		}
	}
}

http://www.verejava.com/?id=16998590966648

已标记关键词 清除标记
自定义对象 ``` 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": [ {...},{....},{...} } } ```
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页