JSON.parseObject,是将Json字符串转化为相应的对象;JSON.toJSONString则是将对象转化为Json字符串。在前后台的传输过程中,Json字符串是相当常用的,这里就不多介绍其功能了,直接举一下应用的小例子,帮助理解这两个方法的用法。
首先用maven引入fastjson
-
<?xml version="1.0" encoding="UTF-8"?>
-
<project xmlns="http://maven.apache.org/POM/4.0.0"
-
xmlns:xsi
=
"http://www.w3.org/2001/XMLSchema-instance"
-
xsi:schemaLocation
=
"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
>
-
<modelVersion>4.0.0
</modelVersion>
-
-
<groupId>com.wujiang.test
</groupId>
-
<artifactId>test
</artifactId>
-
<version>1.0-SNAPSHOT
</version>
-
-
<properties>
-
<fastjson_version>1.2.28
</fastjson_version>
-
</properties>
-
-
<dependencies>
-
<dependency>
-
<groupId>com.alibaba
</groupId>
-
<artifactId>fastjson
</artifactId>
-
<version>${fastjson_version}
</version>
-
</dependency>
-
</dependencies>
-
</project>
定义一个model类,员工,有四个属性,如下所示:
-
package jsonTest;
-
-
import java.util.Date;
-
-
/**
-
*
@author
wujiang
-
*
@version
1.0.0.
-
*
@date
2017/4/30
-
*/
-
public
class Staff {
-
private String name;
-
private Integer age;
-
private String sex;
-
private Date birthday;
-
-
//省略getter和setter方法
-
@Override
-
public
String
toString
() {
-
return
"Staff{" +
-
"name='" + name +
'\'' +
-
", age=" + age +
-
", sex='" + sex +
'\'' +
-
", birthday=" + birthday +
-
'}';
-
}
-
}
好的,下一步,测试一下JSON.parseObject 和 JSON.toJSONString方法。这里故意在Json字符串中多了一个telephone,少了一个Staff中的birthday,看看输出的对象会有什么变化
-
package jsonTest;
-
-
import com.alibaba.fastjson.JSON;
-
-
/**
-
*
@author
wujiang
-
*
@version
1.0.0.
-
*
@date
2017/4/30
-
*/
-
public
class jsonTest {
-
public
static
void
main
(String[] args) {
-
/**
-
* json字符串转化为对象
-
*/
-
String jsonString =
"{name:'Antony',age:'12',sex:'male',telephone:'88888'}";
-
Staff staff = JSON.parseObject(jsonString, Staff.class);
-
System.out.println(staff.toString());
-
-
/**
-
* 对象转化为json字符串
-
*/
-
String jsonStr = JSON.toJSONString(staff);
-
System.out.println(jsonStr);
-
}
-
}
输出结果
-
Staff{name=
'Antony', age=
12, sex=
'male', birthday=
null}
-
-
{
"age":
12,
"name":
"Antony",
"sex":
"male"}
-
//如果age是String类型,那么输出结果变为
-
//{
"age":
"12",
"name":
"Antony",
"sex":
"male"}
在JSON.parseObject 的时候,会去填充名称相同的属性。对于Json字符串中没有,而model类有的属性,会为null;对于model类没有,而Json字符串有的属性,不做任何处理。
至于 JSON.toJSONString 就不需要多说了,看一下就知道
至于应用场景,比方说,用户登录微信公众号的时候,调用微信官方的restful接口,得到该用户的所有信息的一个Json字符串,然后写一个类(将自己需要的信息封装成一个类)。例如下面的伪代码
-
String s = httpRequest
.sendGet(
"https://api.weixin.qq.com/sns/oauth2/access_token",
"appid=" + appId +
"&secret=" + appSecret +
"&code=" + code +
"&grant_type=authorization_code")
;
-
-
UserAuthorizationReturn userAuthorizationReturn = JSON
.parseObject(s, UserAuthorizationReturn
.class)
;
说明:
如有转载,请在文章开头注明出处
http://blog.csdn.net/antony9118/article/details/71023009