Gson初接触

最近在项目中使用到Gson,so cool,于是上官网进一步了解Gson,了解下为何要使用Gson,Gson提供了哪些便利,介绍性文章, 不做深入探讨。


Gson库的目标,官方的说法是

Goals for Gson

* Provide easy to use mechanisms like toString() and constructor (factory method) to convert Java to JSON and vice-versa

* Allow pre-existing unmodifiable objects to be converted to and from JSON

* Allow custom representations for objects

* Support arbitrarily complex object

* Generate compact and readability JSON output

简单来说有几个比较酷的特点吧 

1. 提供了机制能够很方便得实现Java对象和Json字符串的互转。

2. 支持容器和泛型类型。


第1点是我最喜欢的,能够将对象以结构化的形式保存到字符串中。

下面的代码段描述了 Device对象和String的互转

public void testWriteJson(){
		Device device = new Device();
		device.setNickName("class one");
        ...		
		
		Gson gson = new Gson();
		String jsonString = gson.toJson(device);
		
		try {  
			   //write converted json data to a file named "CountryGSON.json"  
			   FileWriter writer = new FileWriter(mFile);  
			   writer.write(jsonString);  
			   writer.close();  
			    
			  } catch (IOException e) {  
			   e.printStackTrace();  
			  }  
	}
	
	public void testReadJson(){
		Gson gson = new Gson();
		
		try {
			BufferedReader br = new BufferedReader(  
				     new FileReader(mFile));
			
			Device device = gson.fromJson(br, Device.class);
			
			{
				Gson gson2 = new Gson();
				String jsonString = gson2.toJson(device);
				Log.i("kesy", jsonString);
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

还有几个有意思的辅助特点

1.  Json字符串默认是没有缩进格式的,gson支持缩进,这在开发调试阶段有所用途,方便肉眼查看。

        Gson gson = new GsonBuilder().setPrettyPrinting().create();

        String jsonOutput = gson.toJson(someObject);

2. Gson导出的Json字符串默认不会记录值为null的field,以减小字符串的字节数,这就要求java有默认值的处理。

3. Gson有版本支持,某种程度上支持数据结构的向后兼容,方便产品的迭代。 

public class VersionedClass {
  @Since(1.1) private final String newerField;
  @Since(1.0) private final String newField;
  private final String field;
  public VersionedClass() {
    this.newerField = "newer";
    this.newField = "new";
    this.field = "old";
  }
}
VersionedClass versionedObject = new VersionedClass();
Gson gson = new GsonBuilder().setVersion(1.0).create();
String jsonOutput = gson.toJson(someObject);
System.out.println(jsonOutput);
System.out.println();
gson = new Gson();
jsonOutput = gson.toJson(someObject);
System.out.println(jsonOutput);
======== OUTPUT ========
{"newField":"new","field":"old"}
{"newerField":"newer","newField":"new","field":"old"}

4. 可以指定哪些field不参与序列化和反序列化,更加灵活

5. 可以更改序列化后域的名称,比如域名称是个相对较长的字符串如"mCurrentTime",你可以在序列化时,改为"ct"





IT是个变化很快的行业,想了解最新,最酷的特性只能上官网去查找。


人类一思考,上帝就发笑。

站在巨人的肩膀上编码的,

并非巨细都出自自己的思考,

难免会有偏差,

若有误,欢迎指正。

------------by jackson.ke


你可能感兴趣的:(json,gson)