Gson解析json字符串、json数组转换成对象

实体类:

public class Product {
private int id;
private String name;
private String date;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}

方法:

public static void main(String[] args) throws IOException, Exception {

//json格式的字符串装换成对象
Gson gson = new Gson();//new一个Gson对象
//json字符串
String json = "{\"name\":\"xiaomi\",\"id\":123456,\"date\":\"2013-4-13 12:36:54\"}";
//new 一个Product对象
Product product = new Product();
//将一个json字符串转换为java对象
product = gson.fromJson(json, Product.class);
//输出
System.out.println("Name:" + product.getName());
System.out.println("Id:" + product.getId());
System.out.println("Date:" + product.getDate());

//json格式的数组装换成对象
//String str = "[{'name':'kevin','age':25},{'name':'cissy','age':24}]";
String str = "[{\"name\":\"array\",\"id\":123456,\"date\":\"2013-4-13 12:36:54\"},{\"name\":\"tom\",\"id\":123,\"date\":\"2013-4-13 12:36:54\"}]";
//创建一个Gson对象
Gson gson = new Gson();
//创建一个JsonParser
JsonParser parser = new JsonParser();
//通过JsonParser对象可以把json格式的字符串解析成一个JsonElement对象
JsonElement el = parser.parse(str);

//把JsonElement对象转换成JsonArray
JsonArray jsonArray = null;
if(el.isJsonArray()){
jsonArray = el.getAsJsonArray();
}

System.out.println(jsonArray);

//遍历JsonArray对象
Product product = null;
Iterator it = jsonArray.iterator();
while(it.hasNext()){
JsonElement e = (JsonElement)it.next();
//JsonElement转换为JavaBean对象
product = gson.fromJson(e, Product.class);

System.out.println("Name:" + product.getName());
System.out.println("Id:" + product.getId());
System.out.println("Date:" + product.getDate());
}

}

你可能感兴趣的:(Gson解析json字符串、json数组转换成对象)