Gson快速使用介绍

google gson 是一个非常轻量的java 对象与json相互转化工具。

入门也非常简单,下面来看几种常用的方法

Java代码   收藏代码
  1. public class Pet{  
  2.       
  3.       
  4.     private String ma;  
  5.       
  6.     private String ses;  
  7.       
  8.     private String add;  
  9.       
  10.     private String oct;  
  11.       
  12.       
  13.     private List<Integer> managers = new ArrayList<Integer>();  
  14.   
  15.        //get set  
  16.   
  17.     }  

以此pet类作为例子

Java代码   收藏代码
  1. Gson g = new Gson();  
  2.         String json = g.toJson(p);  
  3.         Pet pt= g.fromJson(json, Pet.class);  

1   隐藏某个字段 

当然还有特殊要求,必须pet 转化json 所有字段都转化了,现在是隐藏某个字段,很简单,只需使用annotation @Expos 暴露出来就行,需要的加上,不需要的不加

Java代码   收藏代码
  1. @Expose  
  2. private String ma;  
  3. @Expose()  
  4. private String ses;  
  5. @Expose()  
  6. private String add;  
  7.   
  8. private String oct;  

 这是gson 就应该这么new 

Java代码   收藏代码
  1. Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();  
  2.         System.out.println(gson.toJson(p));  
  3.         System.out.println(gson.toJson(oList));  

 2 换属性名字

Java代码   收藏代码
  1.  public class SomeClassWithFields {  
  2.    @SerializedName("name"private final String someField;  
  3.    private final String someOtherField;  
  4.   
  5.    public SomeClassWithFields(String a, String b) {  
  6.      this.someField = a;  
  7.      this.someOtherField = b;  
  8.    }  
  9.  }  
  10.    
  11. //The following shows the output that is generated when serializing an instance of the above example class:  
  12.   
  13.  SomeClassWithFields objectToSerialize = new SomeClassWithFields("a""b");  
  14.  Gson gson = new Gson();  
  15.  String jsonRepresentation = gson.toJson(objectToSerialize);  
  16.  System.out.println(jsonRepresentation);  
  17.   
  18.  ===== OUTPUT =====  
  19.  {"name":"a","someOtherField":"b"}  

 

3 加版本号

Java代码   收藏代码
  1. public class User {  
  2.   private String firstName;  
  3.   private String lastName;  
  4.   @Since(1.0private String emailAddress;  
  5.   @Since(1.0private String password;  
  6.   @Since(1.1private Address address;  
  7. }  

 4 InputStream 转 json

 

Java代码   收藏代码
  1. public List<Message> readJsonStream(InputStream in) throws IOException {  
  2.     JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));  
  3.     try {  
  4.       return readMessagesArray(reader);  
  5.     } finally {  
  6.       reader.close();  
  7.     }  
  8.   }  
  9.   
  10.   public List<Message> readMessagesArray(JsonReader reader) throws IOException {  
  11.     List<Message> messages = new ArrayList<Message>();  
  12.   
  13.     reader.beginArray();  
  14.     while (reader.hasNext()) {  
  15.       messages.add(readMessage(reader));  
  16.     }  
  17.     reader.endArray();  
  18.     return messages;  
  19.   }  
  20.   
  21.   public Message readMessage(JsonReader reader) throws IOException {  
  22.     long id = -1;  
  23.     String text = null;  
  24.     User user = null;  
  25.     List<Double> geo = null;  
  26.   
  27.     reader.beginObject();  
  28.     while (reader.hasNext()) {  
  29.       String name = reader.nextName();  
  30.       if (name.equals("id")) {  
  31.         id = reader.nextLong();  
  32.       } else if (name.equals("text")) {  
  33.         text = reader.nextString();  
  34.       } else if (name.equals("geo") && reader.peek() != JsonToken.NULL) {  
  35.         geo = readDoublesArray(reader);  
  36.       } else if (name.equals("user")) {  
  37.         user = readUser(reader);  
  38.       } else {  
  39.         reader.skipValue();  
  40.       }  
  41.     }  
  42.     reader.endObject();  
  43.     return new Message(id, text, user, geo);  
  44.   }  
  45.   
  46.   public List<Double> readDoublesArray(JsonReader reader) throws IOException {  
  47.     List<Double> doubles = new ArrayList<Double>();  
  48.   
  49.     reader.beginArray();  
  50.     while (reader.hasNext()) {  
  51.       doubles.add(reader.nextDouble());  
  52.     }  
  53.     reader.endArray();  
  54.     return doubles;  
  55.   }  
  56.   
  57.   public User readUser(JsonReader reader) throws IOException {  
  58.     String username = null;  
  59.     int followersCount = -1;  
  60.   
  61.     reader.beginObject();  
  62.     while (reader.hasNext()) {  
  63.       String name = reader.nextName();  
  64.       if (name.equals("name")) {  
  65.         username = reader.nextString();  
  66.       } else if (name.equals("followers_count")) {  
  67.         followersCount = reader.nextInt();  
  68.       } else {  
  69.         reader.skipValue();  
  70.       }  
  71.     }  
  72.     reader.endObject();  
  73.     return new User(username, followersCount);  
  74.   }  

 更多功能请访问http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/index.html 上面代码例子也有的是来自api,api非常详细。

对ztree 里面复杂的json 格式转化非常简单。

 

补充:使用的hibernate的项目 中经常会出现级联对象中,外键对象无法转化出来,或转出来后为null 的现像。例如:

Java代码   收藏代码
  1. */  
  2. @RequestMapping(value = "/getTopicByBroad/{broadId}/{pageIndex}/{pageSize}" , produces = "text/plain;charset=UTF-8")  
  3. @ResponseBody  
  4. public String getTopicByBroad(@PathVariable int broadId,@PathVariable int pageIndex,@PathVariable int pageSize) {  
  5.   
  6.     Page<Topic>  topics = topicService.getTopicByBroad(pageIndex, pageSize, broadId);  
  7.       
  8.     List<Topic> ts = topics.getResult();  
  9.     //此for循环中,对象是有值的,  
  10.     for (Topic topic : ts) {  
  11.         Broad b = topic.getBroad();  
  12.         System.out.println(b.getBroadName());  
  13.     }  
  14.       
  15.     Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();  
  16.     String json = gson.toJson(topics.getResult().get(0).getBroad());  
  17.     System.out.println(json);//broad:{},user:{}无值  
  18.     return json;  
  19. }  

 其实原因很简单,因为hibernate 默认配置了懒加载,

Java代码   收藏代码
  1. @ManyToOne(fetch = FetchType.LAZY)  
  2.     @JoinColumn(name = "user_id")  
  3.     public TtUser getTtUser() {  
  4.         return this.ttUser;  
  5.     }  
  6.   
  7.     public void setTtUser(TtUser ttUser) {  
  8.         this.ttUser = ttUser;  
  9.     }  
  10. //改成eager  
  11.     @ManyToOne(fetch = FetchType.LAZY)  
  12.     @JoinColumn(name = "broad_id")  
  13.     public Broad getBroad() {  
  14.         return this.broad;  
  15.     }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值