java怎么使用gson解析json字符串 java中使用gson解析json的问题
\u5982\u4f55\u7528eclipse\u5b9e\u73b0gson\u89e3\u6790json\u4ee5\u4e00\u4e2a\u7b80\u5355\u7684\u4f8b\u5b50\u6765\u8bf4\u660e\u4e0b\u5427\u3002
\u8fd9\u662f\u4e00\u4e2ajava 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;
}
}
\u4e0b\u8fb9\u662f\u4e00\u4e2aTest\u7c7b
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\u4e00\u4e2aGson\u5bf9\u8c61
//json\u5b57\u7b26\u4e32
String json = "{\"name\":\"guolicheng\",\"id\":123456,\"date\":\"2013-4-13 12:36:54\"}";
//new \u4e00\u4e2aProduct\u5bf9\u8c61
Product product = new Product();
//\u5c06\u4e00\u4e2ajson\u5b57\u7b26\u4e32\u8f6c\u6362\u4e3ajava\u5bf9\u8c61
product = gson.fromJson(json, Product.class);
//\u8f93\u51fa
System.out.println("Name:" + product.getName());
System.out.println("Id:" + product.getId());
System.out.println("Date:" + product.getDate());
}
}
\u8f93\u51fa\u7ed3\u679c\u4e3a\uff1a
Name:guolicheng
Id:123456
Date:2013-04-13 12:36:54.0
\u9996\u5148\u6211\u4e0d\u660e\u767d\u6240\u62a5\u7684\u9519\u662f\u4ec0\u4e48\u9519\uff0c\u5982\u679c\u662f\u8ddfORM\u6846\u67b6\u6709\u5173\u7684\u90a3\u5c31\u662f\u61d2\u52a0\u8f7d\u9020\u6210\u7684\u3002
\u4e00\u822c\u6765\u8bf4\u5bf9\u8c61\u8f6cjson\u4e0d\u90a3\u4e48\u5bb9\u6613\u629b\u9519\u7684\uff0c\u53ea\u6709json\u8f6c\u5bf9\u8c61\u51fa\u9519\u8f83\u9ad8\uff0c\u4f60\u8981\u6ce8\u610f\u7684\u662f\u4f60\u7684\u5bf9\u8c61\u5c5e\u6027\u662f\u5426\u6709\u6807\u51c6\u7684getter\u548csetter\u65b9\u6cd5\u3002
Gson是谷歌推出的解析json数据以及将对象转换成json数据的一个开源框架. 现在json因其易读性和高效率而被广泛的使用着.
相对于java以及其它json的解析框架,Gson非常的好用.
简单来讲就是根据json的数据结构定义出相应的javabean --->"new"出Gson的实例gson---->gson.fromJson(jsonString,JavaBean.class) 即可.
下面给出一个实例来说明.
步骤1:目标:将从webservice传回的json
{
"status": 0,
"result": {
"location": {
"lng": 103.98964143811,
"lat": 30.586643130352
},
"formatted_address": "四川省成都市双流县北一街154",
"business": "簇桥,金花桥",
"addressComponent": {
"city": "成都市",
"district": "双流县",
"province": "四川省",
"street": "北一街",
"street_number": "154"
},
"cityCode": 75
}
}
先普及下json数据格式定义: json数据只有两种格式.
一种是对象: 一个大括号包裹的内容就是一个对象.里面是无数个逗号相间隔的键值对
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" }
一种是数组:一个方括号包裹的内容就是一个数组,里面是无数个逗号相间隔的json对象
如:
{
"people": [
{
"firstName": "Brett",
"lastName": "McLaughlin",
"email": "aaaa"
},
{
"firstName": "Jason",
"lastName": "Hunter",
"email": "bbbb"
},
{
"firstName": "Elliotte",
"lastName": "Harold",
"email": "cccc"
}
]
}
步骤2 定义json数据格式对应的javaBean
public class Result {
private Integerstatus;
private ResultDetailresult;
public Result() {
}
public Result(Integer status, ResultDetail result) {
super();
this.status = status;
this.result = result;
}
public ResultDetail getResult() {
return this.result;
}
public Integer getStatus() {
return this.status;
}
public void setResult( ResultDetail result ) {
this.result = result;
}
public void setStatus( Integer status ) {
this.status = status;
}
@Override
public String toString() {
return "Result [status=" + this.status + ", result=" + this.result
+ "]";
}
}
public class ResultDetail {
Locationlocation;
Stringformatted_address;
AddressComponentaddressComponent;
Stringbusiness;
StringcityCode;
public ResultDetail() {
super();
// TODO Auto-generated constructor stub
}
public ResultDetail(Location location, String formatted_address,
AddressComponent addressComponent, String business, String cityCode) {
super();
this.location = location;
this.formatted_address = formatted_address;
this.addressComponent = addressComponent;
this.business = business;
this.cityCode = cityCode;
}
public AddressComponent getAddressComponent() {
return this.addressComponent;
}
public String getBusiness() {
return this.business;
}
public String getCityCode() {
return this.cityCode;
}
public String getFormatted_address() {
return this.formatted_address;
}
public Location getLocation() {
return this.location;
}
public void setAddressComponent( AddressComponent addressComponent ) {
this.addressComponent = addressComponent;
}
public void setBusiness( String business ) {
this.business = business;
}
public void setCityCode( String cityCode ) {
this.cityCode = cityCode;
}
public void setFormatted_address( String formatted_address ) {
this.formatted_address = formatted_address;
}
public void setLocation( Location location ) {
this.location = location;
}
}
public class Location {
Stringlng;
Stringlat;
public Location() {
}
public Location(String lng, String lat) {
this.lng = lng;
this.lat = lat;
}
public String getLat() {
return this.lat;
}
public String getLng() {
return this.lng;
}
public void setLat( String lat ) {
this.lat = lat;
}
public void setLng( String lng ) {
this.lng = lng;
}
@Override
public String toString() {
return "Location [lng=" + this.lng + ", lat=" + this.lat + "]";
}
}
public class AddressComponent {
Stringcity;
Stringdistrict;
Stringprovince;
Stringstreet;
Stringstreet_number;
public AddressComponent() {
super();
// TODO Auto-generated constructor stub
}
public AddressComponent(String city, String district, String province,
String street, String street_number) {
super();
this.city = city;
this.district = district;
this.province = province;
this.street = street;
this.street_number = street_number;
}
public String getCity() {
return this.city;
}
public String getDistrict() {
return this.district;
}
public String getProvince() {
return this.province;
}
public String getStreet() {
return this.street;
}
public String getStreet_number() {
return this.street_number;
}
public void setCity( String city ) {
this.city = city;
}
public void setDistrict( String district ) {
this.district = district;
}
public void setProvince( String province ) {
this.province = province;
}
public void setStreet( String street ) {
this.street = street;
}
public void setStreet_number( String street_number ) {
this.street_number = street_number;
}
@Override
public String toString() {
return "AddressComponent [city=" + this.city + ", district="
+ this.district + ", province=" + this.province + ", street="
+ this.street + ", street_number=" + this.street_number + "]";
}
}
测试:
jsonString ( 目标json数据,已经在最上面写好的)
System.out.println( "jsonString:" + jsonString );
Gson gson = new Gson();
Result fromJson = gson.fromJson( jsonString.toString() ,Result.class );
System.out.println( "******************************************" );
System.out.println( fromJson );
结果:
jsonString:{"status":0,"result":{"location":{"lng":103.98964143811,"lat":30.586643130352},"formatted_address":"四川省成都市双流县北一街154","business":"簇桥,金花桥","addressComponent":{"city":"成都市","district":"双流县","province":"四川省","street":"北一街","street_number":"154"},"cityCode":75}}
*******************************************
Result [status=0, result=ResultDetail [location=Location [lng=103.98964143811, lat=30.586643130352], formatted_address=四川省成都市双流县北一街154, addressComponent=AddressComponent [city=成都市, district=双流县, province=四川省, street=北一街, street_number=154], business=簇桥,金花桥, cityCode=75]]
可见,jsonString已经成功的被转换成了对应的javaBean
步骤3 : 总结.说明
Gson可以很轻松的实现javaBean和jsonString之间的互转.只需要明白json如何定义.剩下的就非常简单了.
步骤1:目标:将从webservice传回的json
1
{
"status": 0,
"result": {
"location": {
"lng": 103.98964143811,
"lat": 30.586643130352
},
"formatted_address": "四川省成都市双流县北一街154",
"business": "簇桥,金花桥",
"addressComponent": {
"city": "成都市",
"district": "双流县",
"province": "四川省",
"street": "北一街",
"street_number": "154"
},
"cityCode": 75
}
}
2
先普及下json数据格式定义: json数据只有两种格式.
一种是对象: 一个大括号包裹的内容就是一个对象.里面是无数个逗号相间隔的键值对
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" }
一种是数组:一个方括号包裹的内容就是一个数组,里面是无数个逗号相间隔的json对象
如:
{
"people": [
{
"firstName": "Brett",
"lastName": "McLaughlin",
"email": "aaaa"
},
{
"firstName": "Jason",
"lastName": "Hunter",
"email": "bbbb"
},
{
"firstName": "Elliotte",
"lastName": "Harold",
"email": "cccc"
}
]
}
END
步骤2 定义json数据格式对应的javaBean
public class Result {
private Integer status;
private ResultDetail result;
public Result() {
}
public Result(Integer status, ResultDetail result) {
super();
this.status = status;
this.result = result;
}
public ResultDetail getResult() {
return this.result;
}
public Integer getStatus() {
return this.status;
}
public void setResult( ResultDetail result ) {
this.result = result;
}
public void setStatus( Integer status ) {
this.status = status;
}
@Override
public String toString() {
return "Result [status=" + this.status + ", result=" + this.result
+ "]";
}
}
去官网下载jar包,调用方法。
绛旓細姝ラ1:鐩爣:灏嗕粠webservice浼犲洖鐨刯son { "status": 0, "result": { "location": { "lng": 103.98964143811, "lat": 30.586643130352 }, "formatted_address": "鍥涘窛鐪佹垚閮藉競鍙屾祦鍘垮寳涓琛154", "business": "绨囨ˉ,閲戣姳妗", "addressComponent": { "city":...
绛旓細棣栧厛鎴戜滑鍦╡clipse涓垱寤轰竴涓猨ava宸ョ▼锛屽湪java宸ョ▼涓垱寤轰竴涓狧elloWorld鐨勭被锛屽湪杩欎釜java鐨鍏ュ彛绋嬪簭涓紝鎴戜滑鏉ュ垱寤轰竴涓猨son瀛楃涓诧紝骞朵笖鎵撳嵃鍑烘潵锛屽涓嬪浘锛2 灏嗘垜浠垰鍒氬垱寤虹殑json瀛楃涓叉墦鍗板嚭鏉ュ涓嬫墍绀猴紝鍙互鐪嬪嚭杩欎釜json鍖呭惈浜嗕竴涓ぇjson瀵硅薄锛屽ぇjson瀵硅薄閲岄潰鍙堝寘鍚竴涓猨son鏁扮粍锛屼竴涓暟缁勯噷闈㈠張鍖呭惈涓変釜j...
绛旓細姣斿json瀛楃涓蹭负锛歔{"name":"name0","age":0}]Person person = gson.fromJson(str, Person.class);鎻愪緵涓や釜鍙傛暟锛屽垎鍒槸json瀛楃涓蹭互鍙婇渶瑕佽浆鎹㈠璞$殑绫诲瀷銆
绛旓細Gson搴撳湪澶勭悊JSON鏃舵彁渚涗簡鏇村鐨勭伒娲绘э紝濡傚鐞嗙┖鍊笺傜劧鑰岋紝澶勭悊瀛楃涓叉椂锛屽彲鑳介渶瑕浣跨敤閫楀彿鍒嗛殧锛氬綋闇瑕佸皢瀛楃涓叉寜閫楀彿鍒嗛殧涓篔SON鏁扮粍锛屽彲浠ヤ娇鐢╜split()`鏂规硶锛歚String[] values = jsonString.split(",");`濡傛灉瀛楃涓叉湰韬凡缁忔槸JSON鏍煎紡锛屼絾闇瑕佹寜閿煎鎷嗗垎锛屽彲浠ュ厛瑙f瀽涓篔SONObject锛岀劧鍚庤幏鍙栧叾閿...
绛旓細鐢℅son瑙f瀽json鏁版嵁鏄彲浠ョ殑, 濡傛灉浣犻潪瑕佹妸瑙f瀽瀵硅薄鍐欐垚绫诲祵濂楃殑褰㈠紡,灏卞繀椤昏鍙傝僩son鐨勭敤鎴锋寚鍗椼傛渶濂界殑鍔炴硶鏄笉瑕佺敤绫诲祵濂. 鐩存帴鍐欎袱涓被鎺ュ嵆鍙 public class LoginData { public Data Data;public String Detail;public string Return;} public static class Data { public String name;private ...
绛旓細i);//鑾峰彇姣忎竴涓璞 } 杩欎竴绉嶆柟娉曟槸杞崟涓璞℃椂浣跨敤鐨 //gson 杞璞 鍗曚釜瀵硅薄//interactPrize = gson.fromJso(interactPrizeAll,InteractPrize.class);杩欎釜鏂规硶鏄垜鍚庡彴鎷肩殑json寰鍓嶅彴浼犵殑鏂规硶jsonStrAll.append("{"+ "\""+"catid"+"\""+":"+"\""+c.getCatid()+"\""+",...
绛旓細import org.json.JSONObject;try {JSONObject json = new JSONObject();int totalProperty = json.getInt("totalProperty");JSONObject root = json.getJSONObject("root");} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}瑕佸彇浠涔堝煎氨鐢╣etXXX鐨勬柟娉曟潵鍙 ...
绛旓細1銆浣跨敤org.json.JSONArray鍖咃細JSONArray json = new JSONArray(); for(User u : list){ JSONObject jo = new JSONObject(); jo.put("id", u.getId()); jo.put("title", u.getName()); json.put(jo); }2銆佷娇鐢╪et.sf.json鍖呬笅JSONArray鐨勯潤鎬佹柟娉曪細fromObject...
绛旓細import java.io.StringReader;import com.google.gson.stream.JsonReader;public class JsonUtils{public static void parseJson(String jsonData){try{JsonReader reader = new JsonReader(new StringReader(jsonData));reader.beginObject();while(reader.hasNext()){String name = reader.nextName();...
绛旓細濡俙{"name":"寮犱笁", "age":30}`銆傚悓鏍峰湴锛屽鏋滀綘浠嶹eb鏈嶅姟鎺ユ敹鍒颁竴涓狫SON鏍煎紡鐨勫搷搴旓紝浣犱篃鍙互浣跨敤Gson灏嗗叾瑙f瀽涓轰竴涓Java瀵硅薄锛屼粠鑰屾柟渚垮湴鍦ㄤ綘鐨勫簲鐢ㄧ▼搴忎腑浣跨敤杩欎簺鏁版嵁銆傛荤殑鏉ヨ锛孏son鏄竴涓潪甯稿疄鐢ㄧ殑宸ュ叿锛屽畠澶уぇ绠鍖栦簡Java搴旂敤绋嬪簭涓鐞咼SON鏁版嵁鐨勫鏉傛с