创建emp.json文件
[
{
"empno": 110,
"ename": "李白",
"job": "软件工程师",
"hiredate": "2021-01-12",
"salary": 13000,
"dname": "开发部"
},
{
"empno": 111,
"ename": "王维",
"job": "客户经理",
"hiredate": "2020-11-23",
"salary": 23000,
"dname": "市场部",
"customers": [
{
"cname": "小白"
},
{
"cname": "小明"
},
{
"cname": "jack"
}
]
},
{
"empno": 111,
"ename": "杜甫",
"job": "项目经理",
"hiredate": "2000-10-13",
"salary": 30000,
"dname": "市场部"
}
]
sample.html
Insert title here
java的JSON的工具包,把java对象转换成json对象
下载https://github.com/alibaba/fastjson/wiki/Quick-Start-CN
Employee.java
package com.ulikeme.json;
import java.util.Date;
import com.alibaba.fastjson.annotation.JSONField;
public class Employee {
private Integer empno;
private String ename;
private String job;
/**
* 此注解对日期输出进行格式化
*/
@JSONField(format="yyyy-MM-dd")
private Date hdate;
private Float salary;
/**
* 此注解设置不对dname序列化
*/
@JSONField(serialize=false)
private String dname;
public Employee(Integer empno, String ename, String job, Date hdate, Float salary, String dname) {
super();
this.empno = empno;
this.ename = ename;
this.job = job;
this.hdate = hdate;
this.salary = salary;
this.dname = dname;
}
public Integer getEmpno() {
return empno;
}
public void setEmpno(Integer empno) {
this.empno = empno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public Date getHdate() {
return hdate;
}
public void setHdate(Date hdate) {
this.hdate = hdate;
}
public Float getSalary() {
return salary;
}
public void setSalary(Float salary) {
this.salary = salary;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
}
FastJsonSample1.java
package com.ulikeme.json;
import java.util.Calendar;
import com.alibaba.fastjson.JSON;
public class FastJsonSample1 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
//设置时间
Calendar c=Calendar.getInstance();
c.set(2018, 00, 20);
Employee employee=new Employee(110, "李白", "程序员",c.getTime() ,10000f, "开发部");
//FastJson中提供了Json对象,完成对象与json对象的互相转换
String json= JSON.toJSONString(employee);
System.out.println(json);
System.out.println("---------------------");
//将json转换成对象
Employee emp= JSON.parseObject(json, Employee.class);
System.out.println(emp.getEname());
}
}
public class FastJsonSample2 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
List emplist=new ArrayList();
for(int i=1;i<=10;i++) {
Employee employee=new Employee();
employee.setEmpno(100+i);
employee.setEname("员工"+i);
emplist.add(employee);
}
//可以把数组,list,set进行json格式化输出
System.out.println();
String json= JSON.toJSONString(emplist);
System.out.println(json);
//json数组转换成对象
List emps=JSON.parseArray(json,Employee.class);
for(Employee e:emps) {
System.out.println(e.getEname()+":"+e.getEmpno());
}
}
}