本文使用gson对json进行解析处理
首先,下载gson包 ,本文使用(gson-1.6.jar)
1 package com.whroid.java.json; 2 3 import com.google.gson.Gson; 4 5 public class GsonUtil { 6 7 /** 8 * 将json字符串转换成对象。需要保证json中的key和对象的属性名以及属性一致 9 * @param json 10 * @param cls 11 * @return 12 */ 13 public static Object json2Object(String json,Class cls) { 14 Object obj = null; 15 try { 16 Gson gson = new Gson(); 17 obj = gson.fromJson(json, cls); 18 } catch (Exception e) { 19 obj = new Object(); 20 } 21 22 return obj; 23 } 24 25 26 /** 27 * 将对象转换成json字符串 28 * @param object 29 * @return 30 */ 31 public static String object2JsonString(Object object) { 32 if(object == null){ 33 return ""; 34 } 35 Gson gson = new Gson(); 36 return gson.toJson(object).toString(); 37 } 38 39 }
添加实例对象JSONBean(可以不设置getter()/setter()方法,但必须保证属性名和类型一致)
1 package com.whroid.java.json; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 7 public class JSONBean { 8 9 private String name = "name"; 10 private int id = 1; 11 private List<String> list = new ArrayList<String>(); 12 private boolean b; 13 SubBean subBean = new SubBean(); 14 15 @Override 16 public String toString() { 17 return "JSONBean [name=" + name + ", id=" + id + ", list=" + list 18 + ", b=" + b + ", subBean=" + subBean + "]"; 19 } 20 21 22 } 23 class SubBean{ 24 String subname = "subname"; 25 26 27 @Override 28 public String toString() { 29 return "SubBean [subname=" + subname + "]"; 30 } 31 32 }
调用介绍
1 public static void main(String[] args) { 2 3 JSONBean bean = new JSONBean(); 4 String gson = GsonUtil.object2JsonString(bean); 5 System.out.println("gson:"+gson); 6 bean = (JSONBean) GsonUtil.json2Object(gson, JSONBean.class); 7 System.out.println("bean:"+bean); 8 9 }
返回结果:
gson:{"name":"name","id":1,"list":[],"b":false,"subBean":{"subname":"subname"}}
//使用解析gson返回的数据,进行对象实例
bean:JSONBean [name=name, id=1, list=[], b=false,
subBean=SubBean [subname=subname]]