您的位置:首页 > 移动开发 > Objective-C

android 读取JSON数据(遍历JSONObject和JSONArray) .

2012-03-09 11:17 567 查看
private String getJson() {
//jsonString中含有比如unicode编码字符\u67ef的话,getString时自动会转化为相应语言字符。
//从服务器获取的数据片段一般为以下格式
/*{"showid":"38f5ef6ae35711e0a046",
"showname":"\u996d\u5c40\u4e5f\u75af\u72c2",
"completed":1,
"paid":1,
"releasedate":"2012-01-23",
"episode_total":"1",
"episode_last":"1",
"show_thumburl":"http:\/\/g4.ykimg.com\/0102641F464F04034A000000000000E09BC52F-62AE-3FA1-E4F0-A62472C09DC0",
"showcreatetime":"2011-09-20 15:07:37",
"showcategory":"\u7535\u5f71",
"deschead":"\u4f20\u8bf4\u4e2d\u7684\u201c\u5929\u4eba\u4e00\u201d\u996d\u9986\uff0c\u6d77\u9c9c\u8d29\u5b50\u8001\u867e\u7c73\u524d\u6765\u5411\u6b63\u8d70\u9709\u8fd0\u7684\u5c01\u8001\u677f\u8ba8\u503a\u3002\u4e0e\u6b64\u540c\u65f6\uff0c\u7edd\u8272\u6027\u611f\u7684\u7f8e\u5973\uff0c\u795e\u79d8\u5a01\u4e25\u7684\u5927\u4eba\u7269\uff0c\u8fc7\u6c14\u7684\u529f\u592b\u660e\u661f\uff0c\u56fd\u5b66\u5927\u5e08\uff0c\u66b4\u53d1\u6237,
\u6d41\u6d6a\u6b4c\u624b\uff0c\u5a01\u4e25\u7684...",
"showtotal_comment":"583",
"reputation":"8.335",
"showtotal_vv":"2952956",
"show_vthumburl":"http:\/\/g3.ykimg.com\/0102641F464F10C6CF0000000000001078AA2C-3507-7A46-AC81-15FBCEC1A241",
"movie_genre":["\u559c\u5267",
"\u5267\u60c5"],
"area":["\u5927\u9646"],
"performer":[{"id":"12657",
"name":"\u5218\u6866",
"character":["\u5c01\u8001\u677f"]},
{"id":"14685",
"name":"\u8303\u4f1f",
"character":["\u8c2d\u5927\u5e08"]},
{"id":"186154",
"name":"\u9ec4\u6e24",
"character":["\u5bb6\u660e"]},
{"id":"21889",
"name":"\u83ab\u5c0f\u68cb",
"character":["\u83ab\u59ae\u5361"]},
{"id":"17725",
"name":"\u4ee3\u4e50\u4e50",
"character":["\u5c0f\u8774\u8776"]},
{"id":"15808",
"name":"\u6881\u51a0\u534e",
"character":["\u8001\u6885"]},
{"id":"17853",
"name":"\u97e9\u7ae5\u751f",
"character":["\u5927\u8001\u603b"]},
{"id":"16635",
"name":"\u5218\u4e9a\u6d25",
"character":["\u8521\u7259\u91d1"]},
{"id":"161699",
"name":"\u51af\u74c5",
"character":["\u72d7\u72d7"]},
{"id":"228705",
"name":"\u5df4\u591a",
"character":["\u8001\u867e\u7c73"]}],
"firstepisode_videourl":"http:\/\/v.youku.com\/v_show\/id_XMzU4MTA3Mjc2.html",
"showlink":"http:\/\/www.youku.com\/show_page\/id_z38f5ef6ae35711e0a046.html",
"quality":"\u8d85\u6e05"},*/
String jsonString = "{\"FLAG\":\"flag\",\"MESSAGE\":\"SUCCESS\",\"name\":[{\"name\":\"jack\"},{\"name\":\"lucy\"}]}";
try {
Log.d("debugTest","jsonString -- "+jsonString);
JSONObject result = new JSONObject(jsonString);//转换为JSONObject
//			int num = result.length();
JSONArray nameList = result.getJSONArray("name");//获取JSONArray
int length = nameList.length();
String aa = "";
for(int i = 0; i < length; i++) {//遍历JSONArray

JSONObject oj = nameList.getJSONObject(i);
aa = aa + oj.getString("name")+"|";
Log.d("debugTest",Integer.toString(i)+"  aa-- "+aa);
}
Iterator<?> it = result.keys();
String aa2 = "";
String bb2 = null;
while(it.hasNext()){//遍历JSONObject
bb2 = (String) it.next().toString();
aa2 = aa2 + result.getString(bb2);
Log.d("debugTest",bb2+" -- "+aa2);
}
Log.d("debugTest","aa2 -- "+aa2);
return aa;
} catch (JSONException e) {
throw new RuntimeException(e);
}
/*LOG结果:
D/debugTest( 4291): jsonString -- {"FLAG":"flag","MESSAGE":"SUCCESS","name":[{"name":"jack"},{"name":"lucy"}]}
D/debugTest( 4291): 0  aa-- jack|
D/debugTest( 4291): 1  aa-- jack|lucy|
D/debugTest( 4291): FLAG -- flag
D/debugTest( 4291): MESSAGE -- flagSUCCESS
D/debugTest( 4291): name -- flagSUCCESS[{"name":"jack"},{"name":"lucy"}]
D/debugTest( 4291): aa2 -- flagSUCCESS[{"name":"jack"},{"name":"lucy"}]*/

}


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类抛出的异常信息。

一个好用的工具JsonViewer

Json的数据格式可读性较差,但是借助这个工具,可以清晰看出它的数据结构。

官方地址 http://jsonviewer.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=5432
读取Json数据
public String getJson(){
String jsonString = "{\"FLAG\":\"flag\",\"MESSAGE\":\"SUCCESS\",\"name\":[{\"name\":\"jack \"},{\"name\":\"lucy\"}]}";//json字符串
try {
JSONObject result = new JSONObject(jsonstring);//转换为JSONObject
int num = result.length();
JSONArray nameList = result.getJSONArray("name");//获取JSONArray
int length = nameList.length();
String aa = "";
for(int i = 0; i < length; i++){//遍历JSONArray
Log.d("debugTest",Integer.toString(i));
JSONObject oj = nameList.getJSONObject(i);
aa = aa + oj.getString("name")+"|";

}
Iterator<?> it = result.keys();
String aa2 = "";
String bb2 = null;
while(it.hasNext()){//遍历JSONObject
bb2 = (String) it.next().toString();
aa2 = aa2 + result.getString(bb2);

}
return aa;
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: