您好,欢迎访问三七文档
当前位置:首页 > 机械/制造/汽车 > 机械/模具设计 > Android利用Gson实现对象和Json数据的相互转换
Android利用Gson实现对象和Json数据的相互转换MainActitity如下:packagecc.test;importandroid.app.Activity;importandroid.os.Bundle;/***Demo描述:*利用Gson实现对象和Json数据的相互转换**Demo描述:*通过一个网络请求,获取JSON数据**注意:*1网络请求的参数是JSON格式的数据*2请求结果返回的亦是JSON格式的数据**/publicclassMainActivityextendsActivity{@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);init();}privatevoidinit(){newThread(){publicvoidrun(){GetJsonDataByPosthttpJsonPost=newGetJsonDataByPost();String[]pathArray=httpJsonPost.getPathArray(dev0003);for(inti=0;ipathArray.length;i++){System.out.println(pathArray[i]);}}}.start();}}GetJsonDataByPost如下:packagecc.test;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.io.UnsupportedEncodingException;importorg.apache.http.HttpResponse;importorg.apache.http.client.ClientProtocolException;importorg.apache.http.client.methods.HttpPost;importorg.apache.http.entity.StringEntity;importorg.apache.http.impl.client.DefaultHttpClient;importorg.apache.http.params.HttpConnectionParams;importorg.apache.http.protocol.HTTP;publicclassGetJsonDataByPost{staticprivateStringService_URL=Yoururl;staticprivateintTIMEOUT=120*1000;StringmMethodName;publicString[]getPathArray(Stringdevnum){try{mMethodName=GetPicByUser;String[]pathArray=null;//将调用API的参数封装成JSON格式StringjsonParams=JsonUtils.getJsonRequestParams(devnum);//返回的JSON数据StringjsonResult=getJsonDataByPost(jsonParams);//从返回的JSON数据获取其包含的一个数组pathArray=JsonUtils.getJsonRequestResponse(jsonResult);returnpathArray;}catch(Exceptione){e.printStackTrace();}returnnull;}publicStringgetJsonDataByPost(Stringjson){Stringresult=null;try{StringEntityentity=newStringEntity(json,HTTP.UTF_8);entity.setContentType(application/json);DefaultHttpClientclient=newDefaultHttpClient();client.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT,TIMEOUT);client.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT,TIMEOUT);if(mMethodName==null){returnnull;}HttpPosthttpPost=newHttpPost(Service_URL+mMethodName);httpPost.setEntity(entity);HttpResponseresponse=client.execute(httpPost);InputStreaminputStream=response.getEntity().getContent();StringBufferbuffer=newString();InputStreamReaderinputReader=newInputStreamReader(inputStream);BufferedReaderbufferReader=newBufferedReader(inputReader);Stringstr=newString();while((str=bufferReader.readLine())!=null){buffer.append(str);}bufferReader.close();result=buffer.toString();System.out.println(---API的请求结果result=+result);}catch(UnsupportedEncodingExceptione){e.printStackTrace();}catch(ClientProtocolExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}returnresult;}}JsonUtils如下:packagecc.test;importcom.google.gson.Gson;importcom.google.gson.JsonSyntaxException;publicclassJsonUtils{//该对象用于封装请求API的参数.//请求时会将该对象转换为JSON格式的数据staticclassJsonRequestParams{Stringdevsn;intuploadid;floathealthScore;}//该对象用于封装请求API返回后的结果.//即会将JSON格式的数据结果封装成该对象staticclassJsonRequestResult{Stringresultcode;intuploadid;String[]pics;floatbeat;Stringcrtime;}//将请求的参数封装成JSON的格式publicstaticStringgetJsonRequestParams(Stringdevnum){try{JsonRequestParamsjsonRequestParams=newJsonRequestParams();jsonRequestParams.devsn=devnum;jsonRequestParams.uploadid=0;jsonRequestParams.healthScore=0.0f;Gsongson=newGson();//将对象转换为JSON数据StringjsonRequestParamsString=gson.toJson(jsonRequestParams);System.out.println(---封装后的API请求参数jsonRequestParamsString=+jsonRequestParamsString);returnjsonRequestParamsString;}catch(Exceptione){e.printStackTrace();}returnnull;}publicstaticString[]getJsonRequestResponse(Stringret){try{Gsongson=newGson();//将返回的JSON数据转换为对象JsonRequestResultJsonRequestResultmJsonGetPicResponse=gson.fromJson(ret,JsonRequestResult.class);if(mJsonGetPicResponse.resultcode.contains(ok)){//从对象中获取除pics外的各个字段且输出显示System.out.println(---mJsonGetPicResponse.resultcode=+mJsonGetPicResponse.resultcode);System.out.println(---mJsonGetPicResponse.beat=+mJsonGetPicResponse.beat);System.out.(---mJsonGetPicResponse.uploadid=+mJsonGetPicResponse.uploadid);System.out.println(---mJsonGetPicResponse.crtime=+mJsonGetPicResponse.crtime);//从对象中获取pics字段,且返回returnmJsonGetPicResponse.pics;}}catch(JsonSyntaxExceptione){e.printStackTrace();}returnnull;}}main.xml如下:?xmlversion=1.0encoding=utf-8?RelativeLayoutxmlns:android=:layout_width=fill_parentandroid:layout_height=fill_parentandroid:background=#ffffffTextViewandroid:layout_width=wrap_contentandroid:layout_height=wrap_contentandroid:text=HelloEveryoneandroid:layout_centerInParent=true//RelativeLayout
本文标题:Android利用Gson实现对象和Json数据的相互转换
链接地址:https://www.777doc.com/doc-4005485 .html