Gson是 Google 提供的用来在 Java 对象和 Json数据之间进行相互转换的类库。
第三方jar包下载地址:http://download.youkuaiyun.com/detail/qq906418219/9592202
Github项目地址:https://github.com/google/gson
常用的方法:
1、toJson方法把Java对象转化为Json字符串。
2、fromJson方法把Json字符串转化为Java对象。
简单例子:
1、首先编写一个简单的Bean类
class Bean{
int code;
String message;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}2、使用toJson方法
public static void main(String[] args) {
Gson gson = new Gson();
Bean bean = new Bean();
bean.setCode(200);
bean.setMessage("ok");
String json = gson.toJson(bean);
System.out.println(json);
}输出结果:>`{"code":200,"message":"ok"}`
3、使用FromJson方法
public class TestMain {
public static void main(String[] args) {
<span style="white-space:pre"> </span>Gson gson = new Gson();
<span style="white-space:pre"> </span>Bean bean = new Bean();
bean.setCode(200);
bean.setMessage("ok");
String json = gson.toJson(bean);
System.out.println(json);
}
}
输出结果:code:201
message:ok
注意事项:
1、在数据转换中一定要保持数据名称和类型一致或者数据能够进行强制转换,比如code字段为int,你在Bean中定义可以为int,String,Long等,不然会抛出错误。
2、Json中数据类型:有双引号为字符,没有双引号通常为int,long或者非基本数据类型,例如{...}为类,[...]为数组(会以逗号分割),[ [...] ]为二维数组(三维四维类推)。
这就是Gson的基本使用,但往往在实践问题中Json数据会比上文更加复杂。
本文源码地址:https://github.com/CoderDog/TestGson
Gson是Google提供的Java对象和Json数据转换类库。本文介绍了如何使用toJson和fromJson方法进行转换,并给出了简单的示例。在使用时需要注意数据类型一致或可转换,以及Json数据类型的特性。提供源码地址供进一步学习。
1352

被折叠的 条评论
为什么被折叠?



