Android利用Json来进行网络数据传输
最近做一项目,有很多地方得用到网络数据传输与解析,这里采用的是Json方式,它与传统的XML解析方式比起来,有自己的一些优点,首先,它是比XML更轻量级,再一个,写一个XML文件是个烦人的事儿,而Json则相对轻松些。
Android平台有Jsong相关的类来进行Json数据解析,悲剧的是,它们是Android SDK3.0以后才能用的。不过在谷歌网站:http://code.google.com/p/google-gson/里有一个名为Gson的类库,可以用它来解析Json数据,并且,Adroid 3.0平台里其实也就是把这一部分直接整合进Android里了。我们要解析Json数据,直接去网站上下载个jar包,导入到工程里,就可以解析Json数据了。
下面有个例子,很清晰的解释了这种工作方式:
先看看两个我自己封装的类:
HttpUtils.java:
- publicclassHttpUtils{//从服务器端下载到Json数据,也就是个字符串
- publicstaticStringgetData(Stringurl)throwsException{
- StringBuildersb=newStringBuilder();
- HttpClienthttpClient=newDefaultHttpClient();
- HttpGethttpGet=newHttpGet(url);
- HttpResponsehttpResponse=httpClient.execute(httpGet);
- HttpEntityhttpEntity=httpResponse.getEntity();
- if(httpEntity!=null){
- InputStreaminstream=httpEntity.getContent();
- BufferedReaderreader=newBufferedReader(newInputStreamReader(
- instream));
- Stringline=null;
- while((line=reader.readLine())!=null){
- sb.append(line);
- }
- returnsb.toString();
- }
- returnnull;
- }
JsonUtils.java:
- publicclassJsonUtils{
- publicstaticList<Student>parseStudentFromJson(Stringdata){
- TypelistType=newTypeToken<LinkedList<Student>>(){
- }.getType();
- Gsongson=newGson();
- LinkedList<Student>list=gson.fromJson(data,listType);
- returnlist;
- }
- }
里面的Student是一个JavaBean对象:
- publicclassStudent{
- privateStringname;
- privateintage;
- privateStringid;
- publicStudent(){
- super();
- }
- publicStudent(Stringname,intage,Stringid){
- super();
- this.name=name;
- this.age=age;
- this.id=id;
- }
- publicStringgetName(){
- returnname;
- }
- publicvoidsetName(Stringname){
- this.name=name;
- }
- publicintgetAge(){
- returnage;
- }
- publicvoidsetAge(intage){
- this.age=age;
- }
- publicStringgetId(){
- returnid;
- }
- publicvoidsetId(Stringid){
- this.id=id;
- }
- }
再看看我们要解析网络数据的activity代码
- publicclassMainActivityextendsActivity{
- privateTextViewtextView;
- privateList<Student>list;
- /**Calledwhentheactivityisfirstcreated.*/
- @Override
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- textView=(TextView)findViewById(R.id.textView);
- Stringdata=null;
- try{
- data=HttpUtils
- .getData("http://10.16.12.165:8080/JsonTest/JsonTestServlet");
- }catch(Exceptione){
- e.printStackTrace();
- }
- Stringresult="";
- list=JsonUtils.parseStudentFromJson(data);
- for(Students:list){
- result+="name:"+s.getName()+""+"age:"+s.getAge()
- +""+"id:"+s.getId()+"\n";
- }
- textView.setText(result);
- }
- }
这样就可以获取网络数据并加以解析利用了,运行结果如下: