您的位置:首页 > 移动开发 > Android开发

Android和Json

2012-04-11 11:36 387 查看
JSON的定义:
一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性。业内主流技术为其提供了完整的解决方案(有点类似于正则表达式 ,获得了当今大部分语言的支持),从而可以在不同平台间进行数据交换。JSON采用兼容性很高的文本格式,同时也具备类似于C语言体系的行为。 – Json.org

为什么用JSON?

很简单,因为它比xml快十倍。

有哪些应用案例?

Twitter、豆瓣、facebook等公司的开放api,一般这些服务都会提供多种格式供开发人员选择(xml、json、atom等),而在手机终端上,我们自然希望给用户最佳体验,所以我选用最有效率的json格式。

按照我的文档习惯,将会附上具体demo,在本文档末尾中可找到下载,其中的示例是用豆瓣api。

JSON的结构:

Name/Value Pairs 类似所熟知的Keyed list、Hash table、Disctionary和Associative array。在Android平台中同时存在另外一个类“Bundle”,某种程度上具有相似的行为。
org.json.JSONObject Array,一组有序的数据列表。org.json.JSONArray

Android中 JSON相关的类(4个)和Exceptions(1个):

l JSONArray
l JSONObject
l JSONStringer
l JSONTokener
l JSONException

JSONObject:

这是系统中有关JSON定义的基本单元,其包含一对儿(Key/Value)数值。它对外部(External:应用toString()方法输出的数值)调用的响应体现为一个标准的字符串(例如:{"JSON": "Hello, World"},最外被大括号包裹,其中的Key和Value被冒号":"分隔)。其对于内部(Internal)行为的操作格式略微,例如:初始化一个JSONObject实例,引用内部的put()方法添加数值:new JSONObject().put("JSON", "Hello, World!"),在Key和Value之间是以逗号","分隔。

Value的类型包括:Boolean、JSONArray、JSONObject、Number、String或者默认值JSONObject.NULL object。

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

JSONArray:

它代表一组有序的数值。将其转换为String输出(toString)所表现的形式是用方括号包裹,数值以逗号”,”分隔(例如:[value1,value2,value3],大家可以亲自利用简短的代码更加直观的了解其格式)。这个类的内部同样具有查询行为,get()和opt()两种方法都可以通过index索引返回指定的数值,put()方法用来添加或者替换数值。

同样这个类的value类型可以包括:Boolean、JSONArray、JSONObject、Number、String或者默认值JSONObject.NULL object。

JSONStringer:

根据官方的解释,这个类可以帮助快速和便捷的创建JSON text。其最大的优点在于可以减少由于格式的错误导致程序异常,引用这个类可以自动严格按照JSON语法规则(syntax rules)创建JSON text。每个JSONStringer实体只能对应创建一个JSON text。

根据下边的实例来了解其它相关信息:
string myString = new JSONStringer().object()
.key("AR").value("www.Androidres.com!")
.endObject()
.toString();
结果是一组标准格式的JSON text:{”AR”:”www.Androidres.com!”}

其中的.object()和.endObject()必须同时使用,是为了按照Object标准给数值添加边界。同样,针对数组也有一组标准的方法来生成边界.array()和.endArray()。

JSONTokener:

这个是系统为JSONObject和JSONArray构造器解析JSON source string的类,它可以从source string中提取数值信息。

JSONException:

是JSON.org类抛出的异常信息。

json数据格式解析我自己分为两种;

一种是普通的,一种是带有数组形式的;

普通形式的:
服务器端返回的json数据格式如下:

{"userbean":{"Uid":"100196","Showname":"\u75af\u72c2\u7684\u7334\u5b50","Avtar":null,"State":1}}

分析代码如下:

// TODO 状态处理 500 200
int res = 0;
res = httpClient.execute(httpPost).getStatusLine().getStatusCode();
if (res == 200) {
/*
* 当返回码为200时,做处理
* 得到服务器端返回json数据,并做处理
* */
HttpResponse httpResponse = httpClient.execute(httpPost);
StringBuilder builder = new StringBuilder();
BufferedReader bufferedReader2 = new BufferedReader(
new InputStreamReader(httpResponse.getEntity().getContent()));
String str2 = "";
for (String s = bufferedReader2.readLine(); s != null; s = bufferedReader2
.readLine()) {
builder.append(s);
}
Log.i("cat", ">>>>>>" + builder.toString());

JSONObject jsonObject = new JSONObject(builder.toString())
.getJSONObject("userbean");

String Uid;
String Showname;
String Avtar;
String State;

Uid = jsonObject.getString("Uid");
Showname = jsonObject.getString("Showname");
Avtar = jsonObject.getString("Avtar");
State = jsonObject.getString("State");
带数组形式的:
服务器端返回的数据格式为:

{"calendar":
{"calendarlist":
[
{"calendar_id":"1705","title":"(\u4eb2\u5b50)ddssd","category_name":"\u9ed8\u8ba4\u5206\u7c7b","showtime":"1288927800","endshowtime":"1288931400","allDay":false},
{"calendar_id":"1706","title":"(\u65c5\u884c)","category_name":"\u9ed8\u8ba4\u5206\u7c7b","showtime":"1288933200","endshowtime":"1288936800","allDay":false}
]
}
}

分析代码如下:

// TODO 状态处理 500 200
int res = 0;
res = httpClient.execute(httpPost).getStatusLine().getStatusCode();
if (res == 200) {
/*
* 当返回码为200时,做处理
* 得到服务器端返回json数据,并做处理
* */
HttpResponse httpResponse = httpClient.execute(httpPost);
StringBuilder builder = new StringBuilder();
BufferedReader bufferedReader2 = new BufferedReader(
new InputStreamReader(httpResponse.getEntity().getContent()));
String str2 = "";
for (String s = bufferedReader2.readLine(); s != null; s = bufferedReader2
.readLine()) {
builder.append(s);
}
Log.i("cat", ">>>>>>" + builder.toString());
/**
* 这里需要分析服务器回传的json格式数据,
*/
JSONObject jsonObject = new JSONObject(builder.toString())
.getJSONObject("calendar");
JSONArray jsonArray = jsonObject.getJSONArray("calendarlist");
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject2 = (JSONObject)jsonArray.opt(i);
CalendarInfo calendarInfo = new CalendarInfo();
calendarInfo.setCalendar_id(jsonObject2.getString("calendar_id"));
calendarInfo.setTitle(jsonObject2.getString("title"));
calendarInfo.setCategory_name(jsonObject2.getString("category_name"));
calendarInfo.setShowtime(jsonObject2.getString("showtime"));
calendarInfo.setEndtime(jsonObject2.getString("endshowtime"));
calendarInfo.setAllDay(jsonObject2.getBoolean("allDay"));
calendarInfos.add(calendarInfo);
}

总结,普通形式的只需用JSONObject ,带数组形式的需要使用JSONArray 将其变成一个list。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息