javajsontostring
① 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