如何用eclipse实现gson解析json
1个回答
展开全部
以一个简单的例子来说明下吧。
这是一个java Bean
package baz.javabean;
import java.sql.Timestamp;
public class Product {
private String name;
private int id;
private Timestamp date;
public Product() {
// TODO Auto-generated constructor stub
}
public Product(String name, int id, Timestamp date) {
super();
this.name = name;
this.id = id;
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Timestamp getDate() {
return date;
}
public void setDate(Timestamp date) {
this.date = date;
}
}
下边是一个Test类
package baz.test;
import baz.javabean.Product;
import com.google.gson.Gson;
public class Test1 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Gson gson = new Gson();//new一个Gson对象
//json字符串
String json = "{\"name\":\"guolicheng\",\"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());
}
}
输出结果为:
Name:guolicheng
Id:123456
Date:2013-04-13 12:36:54.0
这是一个java Bean
package baz.javabean;
import java.sql.Timestamp;
public class Product {
private String name;
private int id;
private Timestamp date;
public Product() {
// TODO Auto-generated constructor stub
}
public Product(String name, int id, Timestamp date) {
super();
this.name = name;
this.id = id;
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Timestamp getDate() {
return date;
}
public void setDate(Timestamp date) {
this.date = date;
}
}
下边是一个Test类
package baz.test;
import baz.javabean.Product;
import com.google.gson.Gson;
public class Test1 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Gson gson = new Gson();//new一个Gson对象
//json字符串
String json = "{\"name\":\"guolicheng\",\"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());
}
}
输出结果为:
Name:guolicheng
Id:123456
Date:2013-04-13 12:36:54.0
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |