1、写好一个实体类,这里以Student.java为例
public class Student {
private int id;
private String name;
private int age;
private String sex;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
2、重写bean类的toString方法(第一次使用json需要配置json的模板)
3、自己新建一个自定义的模板,然后在右侧输入生成json模板的代码
public java.lang.String toString() {
final java.lang.StringBuilder sb = new java.lang.StringBuilder("{");
#set ($i = 0)
#foreach ($member in $members)#if ($i == 0)
sb.append("#####
#else
sb.append(",####
#end#if ($member.string || $member.date)
\"$member.name\":\"")
#else
\"$member.name\":")
#end#if ($member.primitiveArray || $member.objectArray)
.append(java.util.Arrays.toString($member.name));
#elseif ($member.string || $member.date)
.append($member.accessor).append('\"');
#else
.append($member.accessor);
#end#set ($i = $i + 1)
#end
sb.append('}');
return sb.toString();
}
4、后续重写bean.toString()方法的时候就直接生成json类型的了
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("{");
sb.append("\"id\":")
.append(id);
sb.append(",\"name\":\"")
.append(name).append('\"');
sb.append(",\"age\":")
.append(age);
sb.append(",\"sex\":\"")
.append(sex).append('\"');
sb.append('}');
return sb.toString();
}
此时bean就转换成json字符串了
bean转换成json
Student stu = new Student();
stu.setAge(11);
stu.setId(1000);
stu.setName("小明");
stu.setSex("男");
String json = stu.toString();
System.out.println("json="+json);
输出结果: json={"id":1000,"name":"小明","age":11,"sex":"男"}
json字符串转成bean
Student bean = JSONObject.parseObject(json,Student.class);
System.out.println("bean="+bean);
输出结果:bean={"id":1000,"name":"小明","age":11,"sex":"男"}
------end------