當前位置:首頁 » 編程語言 » javajsontostring

javajsontostring

發布時間: 2024-07-10 17:31:32

java怎麼使用gson解析json字元串

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


publicclassResult{
privateIntegerstatus;
privateResultDetailresult;
publicResult(){
}
publicResult(Integerstatus,ResultDetailresult){
super();
this.status=status;
this.result=result;
}
publicResultDetailgetResult(){
returnthis.result;
}
publicIntegergetStatus(){
returnthis.status;
}
publicvoidsetResult(ResultDetailresult){
this.result=result;
}
publicvoidsetStatus(Integerstatus){
this.status=status;
}
@Override
publicStringtoString(){
return"Result[status="+this.status+",result="+this.result
+"]";
}
}
publicclassResultDetail{
Locationlocation;
Stringformatted_address;
;
Stringbusiness;
StringcityCode;
publicResultDetail(){
super();
//TODOAuto-generatedconstructorstub
}
publicResultDetail(Locationlocation,Stringformatted_address,
,Stringbusiness,StringcityCode){
super();
this.location=location;
this.formatted_address=formatted_address;
this.addressComponent=addressComponent;
this.business=business;
this.cityCode=cityCode;
}
(){
returnthis.addressComponent;
}
publicStringgetBusiness(){
returnthis.business;
}
publicStringgetCityCode(){
returnthis.cityCode;
}
publicStringgetFormatted_address(){
returnthis.formatted_address;
}
publicLocationgetLocation(){
returnthis.location;
}
publicvoidsetAddressComponent(){
this.addressComponent=addressComponent;
}
publicvoidsetBusiness(Stringbusiness){
this.business=business;
}
publicvoidsetCityCode(StringcityCode){
this.cityCode=cityCode;
}
publicvoidsetFormatted_address(Stringformatted_address){
this.formatted_address=formatted_address;
}
publicvoidsetLocation(Locationlocation){
this.location=location;
}
}
publicclassLocation{
Stringlng;
Stringlat;
publicLocation(){
}
publicLocation(Stringlng,Stringlat){
this.lng=lng;
this.lat=lat;
}
publicStringgetLat(){
returnthis.lat;
}
publicStringgetLng(){
returnthis.lng;
}
publicvoidsetLat(Stringlat){
this.lat=lat;
}
publicvoidsetLng(Stringlng){
this.lng=lng;
}
@Override
publicStringtoString(){
return"Location[lng="+this.lng+",lat="+this.lat+"]";
}
}
publicclassAddressComponent{
Stringcity;
Stringdistrict;
Stringprovince;
Stringstreet;
Stringstreet_number;
publicAddressComponent(){
super();
//TODOAuto-generatedconstructorstub
}
publicAddressComponent(Stringcity,Stringdistrict,Stringprovince,
Stringstreet,Stringstreet_number){
super();
this.city=city;
this.district=district;
this.province=province;
this.street=street;
this.street_number=street_number;
}
publicStringgetCity(){
returnthis.city;
}
publicStringgetDistrict(){
returnthis.district;
}
publicStringgetProvince(){
returnthis.province;
}
publicStringgetStreet(){
returnthis.street;
}
publicStringgetStreet_number(){
returnthis.street_number;
}
publicvoidsetCity(Stringcity){
this.city=city;
}
publicvoidsetDistrict(Stringdistrict){
this.district=district;
}
publicvoidsetProvince(Stringprovince){
this.province=province;
}
publicvoidsetStreet(Stringstreet){
this.street=street;
}
publicvoidsetStreet_number(Stringstreet_number){
this.street_number=street_number;
}
@Override
publicStringtoString(){
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);
Gsongson=newGson();
ResultfromJson=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如何定義.剩下的就非常簡單了.

② java實體類怎麼轉換成json。

導入Google的包gson-2.2.4.jar
然後實例化Gson
static Gson gosn = new Gson();
String json = gosn.toJson(hashMap); //這里放一個對象,什麼對象都可以。
轉化後就是Json,功能強大很多,也簡單很多。

json-lib-2.4-jdk15.jar
ezmorph-1.0.6.jar
轉換的話這樣用
String s= JSONArray.fromObject(user).toString();

spring-webmvc4
在方法上加入@ResponseBody,同時方法返回值為實體對象,spring會自動將對象轉換為json格式,並返回到客戶端

③ java如何返回json格式

例如:
Student st1 = new Student(1, "dg", 18, new Date());
Student st2 = new Student(2, "dg", 18, new Date());
Student st3 = new Student(3, "dg", 18, new Date());
Student st4 = new Student(4, "dg", 18, new Date());
Student st5 = new Student(5, "dg", 18, new Date());
List li = new ArrayList();
JSONObject JO1 = new JSONObject(st1);
JSONObject JO2 = new JSONObject(st2);
JSONObject JO3 = new JSONObject(st3);
JSONObject JO4 = new JSONObject(st4);
JSONObject JO5 = new JSONObject(st5);
li.add(JO1);
li.add(JO2);
li.add(JO3);
li.add(JO4);
li.add(JO5);
JSONArray Ja = new JSONArray(li);
Map ma = new HashMap();
ma.put("Result", "OK");
ma.put("Records", Ja);
JSONObject js = new JSONObject(ma);
out.print(js);

返回結果:

{"Result":"OK","Records":[{"recordDate":"Fri Dec 16 17:54:39 CST 2011","name":"dg","age":18,"personId":1},{"recordDate":"Fri Dec 16 17:54:39 CST 2011","name":"dg","age":18,"personId":2},{"recordDate":"Fri Dec 16 17:54:39 CST 2011","name":"dg","age":18,"personId":3},{"recordDate":"Fri Dec 16 17:54:39 CST 2011","name":"dg","age":18,"personId":4},{"recordDate":"Fri Dec 16 17:54:39 CST 2011","name":"dg","age":18,"personId":5}]}

④ java中如何讀取json文件,在本地有E:/a.json文件,想讀取這個json文件裡面的內容,怎樣實現

//saveJsonFile("E:\\yindd\\岩模slaughter.json");
//json文件存放路徑(如:E:\a.json)
String data= ReadFile.readFile("F:\\a.json");
System.out.println(data);
JSONObject jsonObj = JSONObject.fromObject(data);
//得到A對粗並緩象
JSONArray arrayA=jsonObj.getJSONArray("A");
A a = (A) JSONObject.toBean((JSONArray.fromObject(arrayA.toString()).getJSONObject(0)),A.class);
//得到B集合蔽歷
JSONArray arrayB=jsonObj.getJSONArray("B");
List<B> listB=new ArrayList<B>();
for(int i=0;i<arrayB.size();i++){
B b=(B)JSONObject.toBean((JSONArray.fromObject(arrayB.toString()).getJSONObject(i)),B.class);
listB.add(b);
}
//得到C集合
JSONArray arrayC=jsonObj.getJSONArray("C");
List<C> listC=new ArrayList<C>();
for(int i=0;i<arrayB.size();i++){
C c=(C)JSONObject.toBean((JSONArray.fromObject(arrayC.toString()).getJSONObject(i)),C.class);
listB.add(c);
}

⑤ Java:ArrayList如何轉換為JSON字元串呢

下一個json的jar包,然後再代碼中使用JSONArray jsonArray = JSONArray.fromObject(/*你的list*/);這樣生成的jsonArray就是一個json字元串。是不是超簡便呢。

⑥ java中怎麼把數據轉換成Json數據

搜json-lib.jar
這個包的例子:
JSONObject obj = new JSONObject();
obj.put("name", "kotomi");
obj.toString();
得到:{"name":"kotomi"}
也可以吧自己定義的實體轉,如
JSONObject.fromObject(xxx);
xxx是你自己定義的實體,他會吧xxx里提供了getter的都轉成json

熱點內容
去哪裡找自己的支付密碼 發布:2024-10-25 14:46:18 瀏覽:417
生產文件夾 發布:2024-10-25 14:46:14 瀏覽:705
windows搭建ftp伺服器埠修改 發布:2024-10-25 14:46:11 瀏覽:322
勞拉與馬ftp 發布:2024-10-25 00:21:16 瀏覽:359
奪寶網站源碼 發布:2024-10-25 00:19:02 瀏覽:454
編程文本編輯器 發布:2024-10-25 00:09:28 瀏覽:972
編程徐帥 發布:2024-10-25 00:03:25 瀏覽:307
手機安卓模擬器如何打開文件 發布:2024-10-25 00:02:55 瀏覽:722
pythonday 發布:2024-10-24 23:55:47 瀏覽:425
g編譯c文件 發布:2024-10-24 23:55:03 瀏覽:294