Json是一种类似于XML的通用数据交换格式,具有比XML更高的传输效率.
 
从结构上看,所有的数据(data)最终都可以分解成三种类型:
第一种类型是标量(scalar),也就是一个单独的字符串(string)或数字(numbers),比如"北京"这个单独的词。
第二种类型是序列(sequence),也就是若干个相关的数据按照一定顺序并列在一起,又叫做数组(array)或列表(List),比如"北京,上海"。
第三种类型是映射(mapping),也就是一个名/值对(Name/value),即数据有一个名称,还有一个与之相对应的值,这又称作散列(hash)或字典(dictionary),比如"首都:北京"。
 
 
Json的规格非常简单,只用一个页面几百个字就能说清楚,而且Douglas Crockford声称这个规格永远不必升级,因为该规定的都规定了。
 
1) 并列的数据之间用逗号(",")分隔。
2) 映射用冒号(":")表示。
3) 并列数据的集合(数组)用方括号("[]")表示。
4) 映射的集合(对象)用大括号("{}")表示。
 
-----------------------------------------------------------------
 
最快速入门贴:
 
1. 对象的序列化和反序列化
 
Type listType = new TypeToken<List<String>>() {}.getType(); 
List<String> target = new LinkedList<String>(); 
target.add("blah");
Gson gson = new Gson(); 
String json = gson.toJson(target, listType); 
List<String> target2 = gson.fromJson(json, listType);
 
 OK,最简方案打完收工.
 
2.使用GsonBuilder.
 
GsonBuilder用来生成Gson对象. 规定Gson的序列化和返序列化时的格式等内容.
如:
 Gson gson = new GsonBuilder()     
            .registerTypeAdapter(Id.class, new IdTypeAdapter())   
            .enableComplexMapKeySerialization() 
            .serializeNulls()   
            .setDateFormat(DateFormat.LONG)  
            .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)//会把字段首字母大写
            .setPrettyPrinting() 
            .setVersion(1.0)    
            .create();
 
3. 使用注解,定制序列化字段.
 
默认情况下@Expose注解是不起作用的,除非你用GsonBuilder创建Gson的时候调用了GsonBuilder.excludeFieldsWithoutExposeAnnotation()方法
 
来个例子:
public class User { 
    @Expose private String firstName; 
    @Expose(serialize = false) private String lastName;
    @Expose (serialize = false, deserialize = false) 
    private String emailAddress; 
    private String password;
 }
 
如果你创建Gson对象的时候使用的是new Gson(),toJson()和fromJson()方法将会对全部的字段生效.但是如果你使用的是GsonBuilder并且调用了excludeFieldsWithoutExposeAnnotation()方法.那么:toJson()和fromJson()将不会包括password.因为password没有包含@Expose注解.
序列化的时候将不包括 lastName和emailAddress,因为注解中标明不进行序列化.同样的道理,反序列化时将不包括emailAddress.
注:如果仅仅是想把某些特定的字段包含在外和话,可以使用transient 关键字声明字段.
 
4. 使用注解对序列化名称进行声明
这个简单,上例子都能懂,不解释:
 public class SomeClassWithFields {
   @SerializedName("name")
   private final String someField;  
   private final String someOtherField;  
 
   public SomeClassWithFields(String a, String b) {   
    this.someField = a; 
    this.someOtherField = b; 
  } 
}
 
 ===== OUTPUT =====
 
 {"name":"a","someOtherField":"b"}
 
5. 例用注解,根据版本进行序列化
有的字段不是一开始就有的,会随着版本的升级添加进来,那么在进行序列化和返序列化的时候就会根据版本号来选择是否要序列化.
@Since(版本号)能完美地实现这个功能.
当然,GsonBuilder.setVersion(double)方法需要调用.
例程如下:
 public class User {  
 private String firstName;  
 private String lastName;   
 @Since(1.0) private String emailAddress;  
 @Since(1.0) private String password;
 @Since(1.1) private Address address;
 }
 
还的字段可能,随着版本的升级而删除,那么
@Until(版本号)也能实现这个功能,GsonBuilder.setVersion(double)方法需要调用.
public class User {   
    private String firstName;   
    private String lastName; 
    @Until(1.1) private String emailAddress;   
    @Until(1.1) private String password;
 }
 
 
maven pom.xml 设置
  <dependency>
   <groupId>com.google.code.gson</groupId>
   <artifactId>gson</artifactId>
   <version>2.1</version>
  </dependency>

google-gson 使用及GsonBuilder设置的更多相关文章

  1. 【排错】springboot项目,启动报An attempt was made to call the method com.google.gson.GsonBuilder.setLenient()Lcom/google/gson/GsonBuilder; but it does not exist.

    pom文件新引入:     <dependency>         <groupId>com.google.code.gson</groupId>         ...

  2. An attempt was made to call the method com.google.gson.GsonBuilder.setLenient()Lcom/google/gson/GsonBuilder; but it does not exist. Its class, com.google.gson.GsonBuilder, is available from the foll

    SLF4J: Class path contains multiple SLF4J bindings. SLF4J: Found binding in [jar:file:/G:/sharp/repo ...

  3. [转]Json转换神器之Google Gson的使用

    这几天,因为项目的需要,接触了Google的Gson库,发现这个东西很好用,遂记下简单的笔记,供以后参考.至于Gson是干什么的,有什么优点,请各位同学自行百度.话不多说,切入正题: 1. 下载Gso ...

  4. [转]使用 google gson 转换Timestamp或Date类型为JSON字符串.

    创建类型适配类: import java.lang.reflect.Type; import java.sql.Timestamp; import java.text.DateFormat; impo ...

  5. 使用 google gson 转换Timestamp或Date类型为JSON字符串.

    http://blog.csdn.net/z69183787/article/details/13016289 创建类型适配类: import java.lang.reflect.Type; impo ...

  6. org.json.JSONObject与com.google.gson.Gson

    org.json库为JSON创始人编写的解析JSON的java库,Gson为Google为我们提供的解析JSON格式数据的库. Gson里最重要的对象有2个Gson 和GsonBuilder. Gso ...

  7. 使用 google gson 转换Timestamp为JSON字符串

    package com.test.base; import java.lang.reflect.Type; import java.sql.Timestamp; import java.text.Da ...

  8. Google Gson解析Json数据应用实例

    转自:http://lixigao449778967.blog.163.com/blog/static/24985164201269105928783/ 1.需要的Jar包 1) Google Gso ...

  9. windows中文编码报错 com.google.gson.JsonIOException: java.nio.charset.MalformedInputException: Input length = 1

    昨天碰到一个问题:同一个请求页面,页面经过匹配后调用http的post协议接口,部署在linux环境的没问题,本地Eclipse启动的tomcat也没问题,直接启动本地tomcat却报错了: 18:4 ...

  10. Google Gson使用简介

    1.Google Gson在android studio的使用 gradle:compile 'com.google.code.gson:gson:2.2.4' 2.Gson 注解 @Expose 注 ...

随机推荐

  1. 装饰器 python 你也可以叫语法糖

    1.最简单的装饰器不带入参 def  func(): pass def  decorate(func) def wrapper(): return func() return wrapper 使用 @ ...

  2. 《MySQL:菜鸟入门系列》

    关于数据库相关知识,几乎是互联网从业者逃不开的一个必备技能,特别是对于DB.开发和测试童鞋来说,更显得重要... 关于MySQL,推荐如下几本书: 入门级:<MySQL必知必会> 进阶级: ...

  3. P2176 [USACO14FEB]路障Roadblock

    题目描述 每天早晨,FJ从家中穿过农场走到牛棚.农场由 N 块农田组成,农田通过 M 条双向道路连接,每条路有一定长度.FJ 的房子在 1 号田,牛棚在 N 号田.没有两块田被多条道路连接,以适当的路 ...

  4. vi学习

    刚开始学习vi,所以,一步一步开始 先贴出一个相关的学习链接https://www.cnblogs.com/ranjiewen/p/5901181.html 这个学习链接里面的东西还是比较详细的,但是 ...

  5. 大数据入门第十七天——storm上游数据源 之kafka详解(三)其他问题

    一.kafka文件存储机制 1.topic存储 在Kafka文件存储中,同一个topic下有多个不同partition,每个partition为一个目录,partiton命名规则为topic名称+有序 ...

  6. vue 打包后,后缀名为.woff等字体问题不能用解决办法

    1.打开 build / webpack.prod.conf.js ,找到 module: { rules: utils.styleLoaders({ sourceMap: config.build. ...

  7. flask登录注册简单的例子

    1.主程序 # app.py # Auther: hhh5460 # Time: 2018/10/05 # Address: DongGuan YueHua from functools import ...

  8. opencv配置(转)

    1. 下载安装Opencv,去官网http://opencv.org/即可下载最新版本的Opencv,此处用的是Opencv 2.4.10 安装时傻瓜式的,最新版本的安装就是相当于解压到你指定的安装目 ...

  9. 部署AlwaysOn第三步:集群资源组的健康检测和故障转移

    资源组是由一个或多个资源组成的组,WSFC的故障转移是以资源组为单位的,资源组中的资源是相互依赖的.一个资源所依赖的其他资源必须和该资源处于同一个资源组,跨资源组的依赖关系是不存在的.在任何时刻,每个 ...

  10. 软件工程第二次作业(One who wants to wear the crown, Bears the crown.)

    小镓自述Eclipse使用及自动单元测试技术 因为本人对JAVA有一些兴趣,所以就决定用Eclipse来完成这次作业,从安装Eclipse到学习写代码,最后学会用Junit来进行单元测试.这段过程给我 ...