java json对象的处理,目前有好一些类库,比较著名的有Jackson,Fastjson等。
这里介绍一下google封装的类库gson。
gson和其他现有java json类库最大的不同时gson需要序列化得实体类不需要
使用annotation来标识需要序列化得字段,同时gson又可以通过使用annotation来灵活配置需要序列化的字段。
1)toJason()方法将对象转换成Json字符串
2)fromJson()方法来实现从Json相关对象到java实体的方法。
如:
 
Person person 
  
  =
  
   gson.fromJson(str, Person.
  
  class
  
  );
 
 
List
  
  <
  
  Person
  
  >
  
   ps 
  
  =
  
   gson.fromJson(str, 
  
  new
  
   TypeToken
  
  <
  
  List
  
  <
  
  Person
  
  >>
  
  (){}.getType()); 
 
其中TypeToken,它是gson提供的数据类型转换器,可以支持各种数据集合类型转换。
 
通过使用annotation来灵活配置需要序列化的字段的示例如下,不用太多解释了。
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"}









