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. Android 多用户多缓存的简单处理方案

    需求:1.在缓存中记录用户登录信息.例如:用户名,密码 2.记录用户操作数据.例如:是否记住用户名密码.设置7天内自动登录等 简单设计:1)使用sqlite设计一张用户数据表,有用户名.密码.操作数据 ...

  2. python 爬虫--同花顺-使用代理

    1.http://www.goubanjia.com/  在上面获取 使用http协议的公网IP和端口 参考:https://blog.csdn.net/qq_23934063/article/det ...

  3. SonarQube6.7.4安装部署

    1.准备工作 https://www.sonarqube.org Sonar 是一个用于代码质量管理的开放平台.通过插件机制,Sonar 可以集成不同的测试工具,代码分析工具,以及持续集成工具.比如p ...

  4. python_基础硬件知识

    通过学习这一篇章的内容,回顾了<数字逻辑><计算机组成原理><操作系统> 这几门课的相关知识 有时候,总是要了解一些基本,才能更容易理解程序 以下是我的一些听课记录 ...

  5. ABAP error:CONVT_NO_NUMBER

    今天写了个接口,传入数据到SAP,结果接收后在报表展示时直接报错. 检查后发现数据转换出错,接收到的数据格式混乱. 最后检查了所有地方发现,源系统传入的数据长度为9个字节,但是自己的接收程序,定义数据 ...

  6. NanoPC-T2制作刷机包

    anoPC-T2制作刷机包 前提:到友善的wiki中,仔细看编译uboot.内核.制作刷机包的教程. 准备工作: 1. 虚拟机Ubuntu安装,并安装n多软件可以支撑编译内核等等. 2.  安装交叉编 ...

  7. C# show FTP Download/Upload progress

    https://stackoverflow.com/questions/4591059/download-file-from-ftp-with-progress-totalbytestoreceive ...

  8. Django Rest Framework源码剖析(一)-----认证

    一.简介 Django REST Framework(简称DRF),是一个用于构建Web API的强大且灵活的工具包. 先说说REST:REST是一种Web API设计标准,是目前比较成熟的一套互联网 ...

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

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

  10. WPF编程,将控件所呈现的内容保存成图像的一种方法。

    原文:WPF编程,将控件所呈现的内容保存成图像的一种方法. 版权声明:我不生产代码,我只是代码的搬运工. https://blog.csdn.net/qq_43307934/article/detai ...