Java_Gson json的学习
来源:互联网 发布:seo标题是什么意思 编辑:程序博客网 时间:2024/05/22 15:47
转载请注明出处:http://blog.csdn.net/y22222ly/article/details/52213043
Gson基本使用
下面对json做json->object;object->json操作:
{ "code": 200, "msg": "success", "newslist": [ { "ctime": "2016-03-31", "title": "奇虎360宣布通过私有化决议", "description": "互联网头条", "picUrl": "http://t1.qpic.cn/mblogpic/f01a972dbcc1060fd456/2000", "url": "http://mp.weixin.qq.com/s?__biz=MjM5OTMyODA2MA==&idx=1&mid=402594468&sn=5cd644536b472a283cc1d3f5124a0cab" }, { "ctime": "2016-03-31", "title": "小本生意做什么挣钱十七大小本生意推荐", "description": "创业最前线", "picUrl": "http://zxpic.gtimg.com/infonew/0/wechat_pics_-4225297.jpg/640", "url": "http://mp.weixin.qq.com/s?__biz=MzA3NjgzNDUwMQ==&idx=2&mid=401864059&sn=cfa082e38ba38c7e673b1ce0a075faee" } ]}
首先需要写一个Object类,作为这个json的实体类。这里我使用的IDE为Android Studio,使用GsonFormat插件能一键转换为Object对象。自己写的时候,顺着符号{``[
来写即可,遇到{
表示该字段为对象,遇到[
表明该字段为数组或是集合。
转换后的对象如下
Weather.java
package com.raise.raisestudy.gson.entity;import java.util.List;/** * Created by raise.yang on 16/08/15. */public class NewsInfo { /** * code : 200 * msg : success * newslist : [{"ctime":"2016-03-31","title":"奇虎360宣布通过私有化决议","description":"互联网头条","picUrl":"http://t1.qpic.cn/mblogpic/f01a972dbcc1060fd456/2000","url":"http://mp.weixin.qq.com/s?__biz=MjM5OTMyODA2MA==&idx=1&mid=402594468&sn=5cd644536b472a283cc1d3f5124a0cab"},{"ctime":"2016-03-31","title":"小本生意做什么挣钱十七大小本生意推荐","description":"创业最前线","picUrl":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-4225297.jpg/640","url":"http://mp.weixin.qq.com/s?__biz=MzA3NjgzNDUwMQ==&idx=2&mid=401864059&sn=cfa082e38ba38c7e673b1ce0a075faee"}] */ private int code; private String msg; /** * ctime : 2016-03-31 * title : 奇虎360宣布通过私有化决议 * description : 互联网头条 * picUrl : http://t1.qpic.cn/mblogpic/f01a972dbcc1060fd456/2000 * url : http://mp.weixin.qq.com/s?__biz=MjM5OTMyODA2MA==&idx=1&mid=402594468&sn=5cd644536b472a283cc1d3f5124a0cab */ private List<NewslistBean> newslist; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public List<NewslistBean> getNewslist() { return newslist; } public void setNewslist(List<NewslistBean> newslist) { this.newslist = newslist; } public static class NewslistBean { private String ctime; private String title; private String description; private String picUrl; private String url; public String getCtime() { return ctime; } public void setCtime(String ctime) { this.ctime = ctime; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getPicUrl() { return picUrl; } public void setPicUrl(String picUrl) { this.picUrl = picUrl; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }}
准备工作已做好,下面看Gson如何解析:
json,object互转
String json = ...; Gson gson = new Gson(); //json -> object NewsInfo newsInfo = gson.fromJson(json, NewsInfo.class); //object ->json gson.toJson(newsInfo);
数组的处理
Gson gson = new Gson();int[] ints = {1, 2, 3, 4, 5};String[] strings = {"abc", "def", "ghi"};// Serializationgson.toJson(ints); // ==> [1,2,3,4,5]gson.toJson(strings); // ==> ["abc", "def", "ghi"]// Deserializationint[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class); // ==> ints2 will be same as ints
泛型的处理
泛型的解析,需要通过Gson提供的TypeToken类,获取一个Type.
class Foo<T> { T value;}Gson gson = new Gson();Foo<Bar> foo = new Foo<Bar>();Type fooType = new TypeToken<Foo<Bar>>() {}.getType();gson.toJson(foo,fooType); gson.fromJson(json, fooType);
null对象的处理
当一个对象的某个属性值为null时,Gson在生成json时会忽略掉这个属性。
Persion对象如下:
public class Person { public double height; public String name; public int age; public Person(double height, String name, int age) { this.height = height; this.name = name; this.age = age; } //...get(),set()}
比如:
Gson gson = new Gson(); Person person = new Person(1.72,null,10); Log.d(TAG,gson.toJson(person));// -->{"age":10,"height":1.72}
GsonBuilder
Gson对象有一个很强大的工厂类GsonBuilder,它可以在创建一个特定的Gson对象,用来制定转换规则。
若需要显示 null 对象:
Gson gson = new GsonBuilder().serializeNulls().create(); Person person = new Person(1.72,null,10); Log.d(TAG,gson.toJson(person));// -->{"age":10,"height":1.72,"name":null}
日期的处理
在Person类增加了下例字段:
public Date birthday;
默认日期格式:
Gson gson = new GsonBuilder().serializeNulls().create(); Person person = new Person(1.72,null,10,new Date()); Log.d(TAG,gson.toJson(person));// -->{"age":10,"birthday":"Aug 15, 2016 19:42:52","height":1.72,"name":null}
使用GsonBuilder格式化后的日志格式:
Gson gson = new GsonBuilder(). serializeNulls() .setDateFormat("yyyyMMdd") .create(); Person person = new Person(1.72,null,10,new Date()); Log.d(TAG,gson.toJson(person));// -->{"age":10,"birthday":"20160815","height":1.72,"name":null}
修改映射key名称
后端人员有时下发json也不安套路出牌,若后端下发给我们的是以下json:
{"age":10,"birthday":"20160815","height":1.72,"person_name":null}
但是我们移动端根本不需要这么详细的定义,还是想像之前一样使用name来表示姓名,那可不可以呢,当然可以,使用注解@SerializedName
即可,这样Person修改为:
public double height; @SerializedName("person_name") public String name; public int age; public Date birthday;
@SerializedName
可以指定转换时,字段的key。
Gson gson = new GsonBuilder(). serializeNulls() .setDateFormat("yyyyMMdd") .create(); String person_json = "{\"age\":10,\"birthday\":\"20160815\",\"height\":1.72,\"person_name\":null}"; Person person = gson.fromJson(person_json, Person.class); Log.d(TAG,person.toString());// -->Person{height=1.72, name='null', age=10, birthday=20160815}
忽略某些字段
当我们收到Person信息时,为了持久化数据,应该保存在数据库中,因此会增加一个id字段,Person字段修改如下:
public double _id;//新增 public double height; @SerializedName("person_name") public String name; public int age; public Date birthday;
当然,从后端下发下来的json不带_id
字段也可以直接使用gson.fromJson()自动转换为Person对象,但是当我们将Person转换为json上传到后端时,如果不做处理,会自动的增加_id
这个字段,如下:
Gson gson = new GsonBuilder(). serializeNulls() .setDateFormat("yyyyMMdd") .create(); Person person = new Person(1,1.70,"raise",10, new Date()); Log.d(TAG,gson.toJson(person));// -->{"_id":1.0,"age":10,"birthday":"20160816","height":1.7,"person_name":"raise"}
很明显,我们应该在生成json时,想办法踢掉这个_id
字段,这是Gson提供了新的注解@Expose
,用来显示哪些字段需要转换。
使用了新的注解后,记得在GsonBuilder时增加excludeFieldsWithoutExposeAnnotation()方法,转换的json就不带_id
字段:
Person
public double _id; @Expose //需要显示转换的字段 public double height; @Expose @SerializedName("person_name") public String name; @Expose public int age; @Expose public Date birthday;
Gson gson = new GsonBuilder() .serializeNulls() .excludeFieldsWithoutExposeAnnotation()//只转换带@Expose注解的字段 .setDateFormat("yyyyMMdd") .create(); Person person = new Person(1,1.70,"raise",10, new Date()); Log.d(TAG,gson.toJson(person));// -->{"age":10,"birthday":"20160816","height":1.7,"person_name":"raise"}
参考资料:
http://www.studytrails.com/java/json/java-google-json-parse-json-to-java.jsp
http://blog.csdn.net/lk_blog/article/details/7685169
- Java_Gson json的学习
- JAVA_Gson解析json工具类封装
- json的学习
- json的学习
- json的初步学习
- json的学习
- json的初步学习
- json的初步学习
- Json的学习
- json的学习
- Json的学习例子
- json/Gson的学习
- json的学习
- Json学习笔记之Json的使用
- json学习:JSONArray的应用
- Json的初步学习、接触
- 关于json的学习笔记
- 我的JSON学习过程
- 证明JS是值传递的一种简单方法
- 余数
- android-----GirdView的使用
- (转载)Mybatis 3.1中 Mapper XML 文件 的学习详解
- SPOJ Con-Junctions(树形dp,方案计数)
- Java_Gson json的学习
- 【cocos2d-x从c++到js】回调函数1——按键回调
- StatFs类 获取系统/sdcard存储空间信息
- 将淘宝客链接转换为正常淘宝、天猫商品链接
- Web页面测试总结——控件类
- 9.Fizz Buzz-Fizz Buzz 问题(容易题)
- 编辑距离
- Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get m
- mysql与db2中的varchar(n)