Json字符串与对象的互转

在开发过程中,经常需要和别的系统交换数据,数据交换的格式有XML、JSON等,JSON作为一个轻量级的数据格式比xml效率要高,XML需要很多的标签,这无疑占据了网络流量,JSON在这方面则做的很好,下面先看下JSON的格式:

1
{"name":"JSON","address":"北京市西城区","age":25}//JSON的对象格式的字符串
1
["com.lyq.pojo.Student",{"id":2,"stuno":"211","stuname":"Jane","stusex":"N","db":"mysql"}]//数组对象格式

1、环境准备

​ 要实现JSON与java对象之间的互转,需要借助第三方jar包,此处使用json-lib这个jar包,可以冲此处下载相关jar包,json-lib需要commons-beanutils-1.8.0.jar、commons-collections-3.2.1.jar、commons-lang-2.5.jar、commons-logging-1.1.1.jar、ezmorph-1.0.6.jar 五个包的支持。

json-lib提供了几个类可以完成此功能,例JSONObject、JSONArray从类的名字上可以看出JSONObject转化的应该是对象格式的,而JSONArray转化的则应该是数组对象(即,带[]形式)的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.4</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.2</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>1.0.6</version>
</dependency>

2、Java普通对象和JSON字符串的互转

2.1 Java对象 –》Json字符串

1
2
3
4
5
6
7
8
9
public class Student implements Serializable {
private int id;
private String stuno;
private String stuname;
private String stusex;
private String db;

//此处省略setter和getter
}

​ Java对象转Json字符串:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* Student对象通过JSONObject和JSONArray两种方式转Json字符串
*/
public static void convertObject() {
Student stu = new Student(3, "100", "成武", "M", "Mysql");

//1、使用JSONObject
JSONObject json = JSONObject.fromObject(stu);
//2、使用JSONArray
JSONArray array=JSONArray.fromObject(stu);

String strJson=json.toString();
String strArray=array.toString();

System.out.println("strJson:"+strJson);
System.out.println("strArray:"+strArray);
}

​ 下面为打印结果:

strJson:{“db”:”Mysql”,”id”:3,”stuname”:”成武”,”stuno”:”100”,”stusex”:”M”}
strArray:[{“db”:”Mysql”,”id”:3,”stuname”:”成武”,”stuno”:”100”,”stusex”:”M”}]

​ 两种方法都可以把java对象转化为JSON字符串,只是转化后的结构不同。

2.2 JSON字符串 —》Java对象

​ 首先需要定义两种不同格式的字符串,需要使用\对双引号进行转义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public static void jsonStrToJava(){
//定义两种不同格式的字符串
String objectStr="{\"id\":\"3\",\"stuname\":\"李四\",\"stuno\":\"100\",\"stusex\":\"M\",\"db\":\"Mysql\"}";
String arrayStr="[{\"id\":\"3\",\"stuname\":\"李四\",\"stuno\":\"100\",\"stusex\":\"M\",\"db\":\"Mysql\"}]";

//1、使用JSONObject
JSONObject jsonObject=JSONObject.fromObject(objectStr);
Student stu=(Student)JSONObject.toBean(jsonObject, Student.class);

//2、使用JSONArray
JSONArray jsonArray=JSONArray.fromObject(arrayStr);
//获得jsonArray的第一个元素
Object o=jsonArray.get(0);
JSONObject jsonObject2=JSONObject.fromObject(o);
Student stu2=(Student)JSONObject.toBean(jsonObject2, Student.class);
System.out.println("stu:"+stu);
System.out.println("stu2:"+stu2);
}

​ 下面为打印结果:

stu:Student{id=3, stuno=’100’, stuname=’李四’, stusex=’M’, db=’Mysql’}
stu2:Student{id=3, stuno=’100’, stuname=’李四’, stusex=’M’, db=’Mysql’}

​ 使用JSONObject可以轻松的把JSON格式的字符串转化为java对象,但是使用JSONArray就没那么容易了,因为它有“[]”符号,所以我们这里在获得了JSONArray的对象之后取其第一个元素即我们需要的一个student的变形,然后使用JSONObject轻松获得

3、list和json字符串的互转

3.1 list –》Json字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public void listToJSON(){
Student stu = new Student(4, "101", "王建", "M", "Mysql");
Student stu2 = new Student(5, "102", "李承", "N", "Mysql");

List<Student> lists=new ArrayList<Student>();
lists.add(stu);
lists.add(stu2);
//1、使用JSONObject
//JSONObject listObject=JSONObject.fromObject(lists);//会报错
//2、使用JSONArray
JSONArray listArray=JSONArray.fromObject(lists);

//System.out.println("listObject:"+listObject.toString());
System.out.println("listArray:"+listArray.toString());

}

​ 我把使用JSONObject的方式给注掉了,我们先看注释之前的结果:

net.sf.json.JSONException: ‘object’ is an array. Use JSONArray instead

​ 注释后,正确执行结果为:

listArray:[{“db”:”Mysql”,”id”:4,”stuname”:”王建”,”stuno”:”101”,”stusex”:”M”},{“db”:”Mysql”,”id”:5,”stuname”:”李承”,”stuno”:”102”,”stusex”:”N”}]

3.2 Json字符串 –》list

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public void jsonToList(){
String arrayStr="[{\"id\":\"4\",\"stuname\":\"王建\",\"stuno\":\"101\",\"stusex\":\"M\",\"db\":\"Mysql\"}]";
//转化为list
List<Student> list2=(List<Student>)JSONArray.toList(JSONArray.fromObject(arrayStr), Student.class);

for (Student stu : list2) {
System.out.println(stu);
}
//转化为数组
Student[] ss =(Student[])JSONArray.toArray(JSONArray.fromObject(arrayStr),Student.class);
for (Student student : ss) {
System.out.println(student);
}
}

​ 打印结果:

1
2
Student{id=4, stuno='101', stuname='王建', stusex='M', db='Mysql'}
Student{id=4, stuno='101', stuname='王建', stusex='M', db='Mysql'}

由于字符串的格式为带有“[]”的格式,所以这里选择JSONArray这个对象,它有toArray、toList方法可供使用,前者转化为java中的数组,后者转化为java中的list,由于这里有实体类进行对应,所以在使用时指定了泛型的类型(Student.class),这样就可以得到转化后的对象

4、map和Json字符串的互转

4.1 Map —》Json字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public void mapToJSON(){
Student stu = new Student(3, "100", "成武", "M", "Mysql");
Student stu1 = new Student(4, "101", "王建", "M", "Mysql");

HashMap<String, Student> stuMap = new HashMap<String, Student>();
stuMap.put("first",stu);
stuMap.put("second",stu1);

//1、JSONObject
JSONObject mapObject= JSONObject.fromObject(stuMap);
System.out.println("mapObject"+mapObject.toString());

//2、JSONArray
JSONArray mapArray=JSONArray.fromObject(stuMap);
System.out.println("mapArray:"+mapArray.toString());
}

​ 打印结果为:

1
2
mapObject{"first":{"stusex":"M","id":3,"stuname":"成武","db":"Mysql","stuno":"100"},"second":{"stusex":"M","id":4,"stuname":"王建","db":"Mysql","stuno":"101"}}
mapArray:[{"first":{"stusex":"M","id":3,"stuname":"成武","db":"Mysql","stuno":"100"},"second":{"stusex":"M","id":4,"stuname":"王建","db":"Mysql","stuno":"101"}}]

4.2 Json字符串 —》Map

JSON字符串不能直接转化为map对象,要想取得map中的键对应的值需要别的方式,

1
2
3
4
5
6
7
8
9
public class MyBean {
private Student first;
public Student getFirst() {
return first;
}
public void setFirst(Student first) {
this.first = first;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
public void jsonToMap(){
String strObject="{\"first\":{\"id\":\"3\",\"stuname\":\"成武\",\"stuno\":\"100\",\"stusex\":\"M\",\"db\":\"Mysql\"}}";

//JSONObject
JSONObject jsonObject=JSONObject.fromObject(strObject);
Map map=new HashMap();
map.put("first", Student.class);

//使用了toBean方法,需要三个参数
MyBean my=(MyBean)JSONObject.toBean(jsonObject, MyBean.class, map);
System.out.println(my.getFirst());

}

​ 打印结果为:

1
Student{id=3, stuno='100', stuname='成武', stusex='M', db='Mysql'}

使用toBean()方法是传入了三个参数,第一个是JSONObject对象,第二个是MyBean.class,第三个是一个Map对象。通过MyBean可以知道此类中要有一个first的属性,且其类型为Student,要和map中的键和值类型对应,即,first对应键 first类型对应值的类型。


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!