gson常用用法小结

来源:互联网 发布:nginx module 编写 编辑:程序博客网 时间:2024/05/19 09:01
gson是来自google的十分不错的json转换器,转换起来十分方便,今天小结下其中的一些用法: 

1) 最基本的对象和json相互转换 

POJO: 

public class ModelObject {
  String name;
  int val;
  boolean status;
  double f;
  
  public ModelObject(String name, int val, 
  boolean status, double f) {
    super();
    this.name = name;
    this.val = val;
    this.status = status;
    this.f = f;
  }
  
  @Override
  public String toString() {
    return "ModelObject [name=" + name + ",
    val=" + val + ", status="
    + status + ", f=" + f + "]";
  }
 
相互转换的代码: 


final Gson gson = new Gson();
// original object instantiation
ModelObject modelObject = new ModelObject("myname", 12, true, 2.3);
System.out.println("toJson ---");
System.out.println("Original Java object : " + modelObject);
// converting an object to json object
String json = gson.toJson(modelObject);
System.out.println("Converted JSON string is : " + json);
 
System.out.println("fromJson----");
// getting object from json representation
System.out.println("Original JSON string is : " + json);
// converting json to object
ModelObject modelObject1 = gson.fromJson(json, ModelObject.class);
System.out.println("Converted Java object : " + modelObject1);

输出如下: 

toJson --- 
Original Java object : ModelObject [name=myname, val=12, status=true, f=2.3] 
Converted JSON string is : {"name":"myname","val":12,"status":true,"f":2.3} 
fromJson---- 
Original JSON string is : {"name":"myname","val":12,"status":true,"f":2.3} 
Converted Java object : ModelObject [name=myname, val=12, status=true, f=2.3] 


2) 针对泛型 
   先看一个泛型的例子定义 

  public class GenericModel<T> {
  T value;
  
  public GenericModel(T value) {
    super();
    this.value = value;
  }
  
  @Override
  public String toString() {
    return "Model2 [value=" + value + "]";
  }
}

然后转换方法如下: 
Gson gson = new Gson(); 

System.out.println("A generic object demo"); 
// a generified object 
GenericModel<Integer> model = new GenericModel<>(12); 

// converting to json representation 
String json = gson.toJson(model); 
System.out.println("json representation :" + json); 

// converting back to object 
Type collectionType = new TypeToken<GenericModel<Integer>>() { 
}.getType(); 
GenericModel<Integer> modelObj = gson.fromJson(json, collectionType); 
System.out.println("converted object representation: " + modelObj); 

System.out.println("\nA object from collection framework\n"); 
// for collection framework objects 
List<String> listOfString = new ArrayList<>(); 
listOfString.add("ajduke"); 
listOfString.add("ajduchess"); 

// conversion to json 
String jsonStr = gson.toJson(listOfString); 
System.out.println("json representation :" + jsonStr); 

Type collectionType2 = new TypeToken<List<String>>() { 
}.getType(); 
List<String> listObj = gson.fromJson(jsonStr, collectionType2); 
System.out.println("converted object representation: " + listObj); 

输出: 
A generic object demo 
json representation :{"value":12} 
converted object representation: Model2 [value=12] 

A object from collection framework 

json representation :["ajduke","ajduchess"] 
converted object representation: [ajduke, ajduchess] 

也就是说,GSON把json转换为JAVA泛型对象的时候,要先定义好 
Type collectionType = new TypeToken<GenericModel<Integer>>() { 
}.getType() 
告诉到底用什么类型,然后再用fromjson方法 


3) 使用transient指定不需要转换为json的属性 

public class ModelObject {
  String name;
  transient int val;
  boolean status;
  double f;
  
  public ModelObject(String name, int val, 
   boolean status, double f) {
    super();
    this.name = name;
    this.val = val;
    this.status = status;
    this.f = f;
  }
  
  @Override
  public String toString() {
    return "ModelObject [name=" + name + ",
    val=" + val + ", status="
    + status + ", f=" + f + "]";
  }
}

   则输出的信息中,就不会转换val了. 


  

4) 也可以使用注解,指定哪些是要暴露转换的属性,如: 

@Expose
private Integer businessId;


但这个时候要用
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation() 
.create(); 
BusinessSystem bus = (BusinessSystem) (gson.fromJson(data, 
BusinessSystem.class)); 

这样类似的方式转换; 


5 也可以用map方式

Map<Object, Object> reqMap = new HashMap<Object, Object>();
reqMap.put("productCode", "222");
reqMap.put("contentId", "1111");
reqMap.put("flag", "true");
String body = new Gson().toJson(reqMap);
               System.out.println(body);

 输出:{"flag":"true","productCode":"222","contentId":"1111"}






0 0
原创粉丝点击