欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

探究Android系统中解析JSON数据的方式

程序员文章站 2024-03-06 11:14:25
前言 喜欢在前言里讲一下自己的现状,或许能有共鸣的同学,更多的是留给自己一个纪念,几个月或者几年再回来看的时候还是会很有感慨。今天说说语言,json这种数据格式之前我做服...

前言
喜欢在前言里讲一下自己的现状,或许能有共鸣的同学,更多的是留给自己一个纪念,几个月或者几年再回来看的时候还是会很有感慨。今天说说语言,json这种数据格式之前我做服务器端的时候天天接触,天真的以为json的世界里只有php的json_encode和json_decode,今天当我做客户端的时候,竟然将近一个多小时才搞定json的解析。这里我不是抨击php好坏,只是想说多学点东西,看看你不熟悉的领域,方能开阔自己的视野,方能知道天外有天,方能知道当初你看不上的工作其实你也不一定能很好的完成,扯多了,回来讲解json


什么是json
json(javascript object natation)是一种轻量级的数据交换格式,相比xml这种数据交换格式来说,json相对解析更加简单一些,因此客户端和服务器的数据交换格式往往通过json进行交换

json一共有两种数据结构,一种是以(key/value)对形式存在的无序的jsonobject对象,一个对象以“{”(左花括号)开始,“}”(右花括号)结束。每个“名称”后跟一个“:”(冒号); “名称/值”对之间使用“,”(逗号)

探究Android系统中解析JSON数据的方式

例如:{”name“:"zhengyi.wzy"},这就是一个最简单的json对象,对于这种数据格式,key值必须是string,而value则可以是string,number,object,array等数据类型

探究Android系统中解析JSON数据的方式

另一种数据格式就是有序的value的集合,这种形式被称为是jsonarray,数组是值(value)的有序集合。一个数组以”[“(左中括号)开始,”]“(右中括号)结束。值之间使用”,“(逗号)分隔

探究Android系统中解析JSON数据的方式

android中json相关解析类
android的json解析部分都在包org.json下,主要有以下几个类:

jsonobject
这是系统中有关json定义的基本单元,其包含一对(key/value)数值

它对外部(external:应用tostring()方法输出的数值)调用的响应体现为一个标准的字符串(例如:{“json”: “hello, world”},最外被大括号包裹,其中的key和value被冒号”:”分隔)。其对于内部(internal)行为的操作格式略微,例如:初始化一个jsonobject实例,引用内部的put()方法添加数值:new jsonobject().put(“json”, “hello, world!”),在key和value之间是以逗号”,”分隔

value的类型包括: jsonobjects, jsonarrays, strings, booleans, integers, longs, doubles or null

有两种不同的取值方式:

    get():在确定key存在的条件下使用,否则当无法检索到相关key时,将会抛出一个exception异常信息
    opt():这个方法相对比较灵活,当无法获取所指定数值时,将会返回一个默认值,并不会抛出异常(个人推荐使用这个方法)


jsonarray
它代表一组有序的数值。将其转换为string输出(tostring)所表现的形式是用方括号包裹,数值以逗号”,”分隔(例如:[”alibaba“,”baidu“,“tecent”])

这个类的内部同样具有查询行为,get()和opt()两种方法都可以通过index索引返回指定的数值,put()方法用来添加或者替换数值

同样jsonarray的value类型可以包括:jsonobjects, jsonarrays, strings, booleans, integers, longs, doubles or null


android解析实例
客户端一般从服务器获得都是字符串,直接new一个jsonobject即可,参考程序如下

获取json字符串
这个网址提供了json字符串:http://api.androidhive.info/contacts/, 我们可以开启一个线程发起http请求,获取json字符串,参考代码如下:

  

 private string getjsonbynetwork() { 
    // you can get json by this url 
    final string url = "http://api.androidhive.info/contacts/"; 
    defaulthttpclient httpclient = new defaulthttpclient(); 
    httpget httpget = new httpget(url); 
   
    inputstream inputstream = null; 
    string result = null; 
   
    try { 
      httpresponse response = httpclient.execute(httpget); 
      inputstream = response.getentity().getcontent(); 
   
      // json is utf-8 by default 
      bufferedreader reader = new bufferedreader(new inputstreamreader( 
          inputstream, "utf-8")); 
      stringbuilder sb = new stringbuilder(); 
      string tmp = null; 
   
      while ((tmp = reader.readline()) != null) { 
        sb.append(tmp); 
      } 
   
      result = sb.tostring(); 
    } catch (exception e) { 
      try { 
        if (inputstream != null) { 
          inputstream.close(); 
        } 
      } catch (ioexception se) { 
      } 
    } 
   
    return result; 
  } 

解析json字符串
解析json字符串的步骤一般如下所示:

(1) 创建jsonobject:

  // create a jsonobject 
  jsonobject jsonobject = new jsonobject(result); 


(2) 获取jsonarray,遍历jsonarray数组

  // to get a specific jsonarray 
  jsonarray jsonarray = jsonobject.getjsonarray("contacts"); 
   
  // to get items from the array 
  for (int i = 0; i < jsonarray.length(); i ++) { 
    // todo:traverse the jsonarray 
  } 


(3) 获取jsonobject

  // create a jsonobject 
  jsonobject jsonobject = new jsonobject(result); 
   
  // to get a specific jsonarray 
  jsonarray jsonarray = jsonobject.getjsonarray("contacts"); 
   
  // to get items from the array 
  for (int i = 0; i < jsonarray.length(); i++) { 
    // to get a specific jsonobject 
    jsonobject oneobject = jsonarray.getjsonobject(i); 
  } 


(4)获取特定字符串

  // create a jsonobject 
  jsonobject jsonobject = new jsonobject(result); 
   
  // to get a specific jsonarray 
  jsonarray jsonarray = jsonobject.getjsonarray("contacts"); 
   
  // to get items from the array 
  for (int i = 0; i < jsonarray.length(); i++) { 
    // to get a specific jsonobject 
    jsonobject oneobject = jsonarray.getjsonobject(i); 
   
    // to get a specific string 
    string id = oneobject.getstring("id"); 
    string name = oneobject.getstring("name"); 
   
    log.e("wzy", "id is:" + id + ", name is " + name); 
  } 


解析结果:

  03-05 10:26:08.690: e/wzy(26401): id is:c200, name is ravi tamada 
  03-05 10:26:08.690: e/wzy(26401): id is:c201, name is johnny depp 
  03-05 10:26:08.690: e/wzy(26401): id is:c202, name is leonardo dicaprio 
  03-05 10:26:08.690: e/wzy(26401): id is:c203, name is john wayne 
  03-05 10:26:08.691: e/wzy(26401): id is:c204, name is angelina jolie 
  03-05 10:26:08.691: e/wzy(26401): id is:c205, name is dido 
  03-05 10:26:08.691: e/wzy(26401): id is:c206, name is adele 
  03-05 10:26:08.692: e/wzy(26401): id is:c207, name is hugh jackman 
  03-05 10:26:08.693: e/wzy(26401): id is:c208, name is will smith 
  03-05 10:26:08.693: e/wzy(26401): id is:c209, name is clint eastwood 
  03-05 10:26:08.694: e/wzy(26401): id is:c2010, name is barack obama 
  03-05 10:26:08.694: e/wzy(26401): id is:c2011, name is kate winslet 
  03-05 10:26:08.695: e/wzy(26401): id is:c2012, name is eminem 

上一篇: 实例讲解java定时任务

下一篇: