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:

  1. publicclassHttpUtils{//从服务器端下载到Json数据,也就是个字符串
  2. publicstaticStringgetData(Stringurl)throwsException{
  3. StringBuildersb=newStringBuilder();
  4. HttpClienthttpClient=newDefaultHttpClient();
  5. HttpGethttpGet=newHttpGet(url);
  6. HttpResponsehttpResponse=httpClient.execute(httpGet);
  7. HttpEntityhttpEntity=httpResponse.getEntity();
  8. if(httpEntity!=null){
  9. InputStreaminstream=httpEntity.getContent();
  10. BufferedReaderreader=newBufferedReader(newInputStreamReader(
  11. instream));
  12. Stringline=null;
  13. while((line=reader.readLine())!=null){
  14. sb.append(line);
  15. }
  16. returnsb.toString();
  17. }
  18. returnnull;
  19. }


JsonUtils.java:

  1. publicclassJsonUtils{
  2. publicstaticList<Student>parseStudentFromJson(Stringdata){
  3. TypelistType=newTypeToken<LinkedList<Student>>(){
  4. }.getType();
  5. Gsongson=newGson();
  6. LinkedList<Student>list=gson.fromJson(data,listType);
  7. returnlist;
  8. }
  9. }

里面的Student是一个JavaBean对象:

  1. publicclassStudent{
  2. privateStringname;
  3. privateintage;
  4. privateStringid;
  5. publicStudent(){
  6. super();
  7. }
  8. publicStudent(Stringname,intage,Stringid){
  9. super();
  10. this.name=name;
  11. this.age=age;
  12. this.id=id;
  13. }
  14. publicStringgetName(){
  15. returnname;
  16. }
  17. publicvoidsetName(Stringname){
  18. this.name=name;
  19. }
  20. publicintgetAge(){
  21. returnage;
  22. }
  23. publicvoidsetAge(intage){
  24. this.age=age;
  25. }
  26. publicStringgetId(){
  27. returnid;
  28. }
  29. publicvoidsetId(Stringid){
  30. this.id=id;
  31. }
  32. }

再看看我们要解析网络数据的activity代码

  1. publicclassMainActivityextendsActivity{
  2. privateTextViewtextView;
  3. privateList<Student>list;
  4. /**Calledwhentheactivityisfirstcreated.*/
  5. @Override
  6. publicvoidonCreate(BundlesavedInstanceState){
  7. super.onCreate(savedInstanceState);
  8. setContentView(R.layout.main);
  9. textView=(TextView)findViewById(R.id.textView);
  10. Stringdata=null;
  11. try{
  12. data=HttpUtils
  13. .getData("http://10.16.12.165:8080/JsonTest/JsonTestServlet");
  14. }catch(Exceptione){
  15. e.printStackTrace();
  16. }
  17. Stringresult="";
  18. list=JsonUtils.parseStudentFromJson(data);
  19. for(Students:list){
  20. result+="name:"+s.getName()+""+"age:"+s.getAge()
  21. +""+"id:"+s.getId()+"\n";
  22. }
  23. textView.setText(result);
  24. }
  25. }

这样就可以获取网络数据并加以解析利用了,运行结果如下:


Android利用Json来进行网络数据传输