安卓解析json

Json的数据结构

例如:

1
2
3
4
5
6
7
8
9
10
11
[
{
"authType":"oAuth2" ,
"CAS":"https://auth.bistu.edu.cn" ,
"oAuth2":"https://222.249.250.89:8443" ,
"AndroidUpgrade":"http://m.bistu.edu.cn/upgrade/Android.php" ,
"jwApi":"http://m.bistu.edu.cn/jiaowu" ,
"icampusApi":"http://m.bistu.edu.cn/api" ,
"newsApi":"http://m.bistu.edu.cn/newsapi"
}

]

在这组数据中,[]中的内容是一个json数组 ,数组中存放着用{}包含的json对象(数组的元素),如果有多个{},那么就表明这个json数组中有多个json对象;一个对象中有多个键值对,冒号前面的是键,冒号后面的是值,不同的键值对之间用,分隔开

Json的解析

本例解析该网址获得的json数据http://m.bistu.edu.cn/api/bus.php点击查看,读者可以打开这个网址看看这里存的json数据是什么样的

SecondActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.ahtcfg24;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
* Created by ahtcfg24 on 2015/4/12.
*/

public class SecondActivity extends Activity
{

private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);

textView = (TextView) findViewById(R.id.textView2);

AsyncHttpClient client = new AsyncHttpClient();
client.get("http://m.bistu.edu.cn/api/bus.php", null, new AsyncHttpResponseHandler() {
@Override
public void onFailure(int arg0, Header[] arg1, byte[] arg2,
Throwable arg3)
{

}

@Override
/**@param responseBody 获得的byte数组里存放的是从网址里获取到的数据的ASCII编码格式*/
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
/*这里的data是将ASCII编码转换过后的字符串*/
String data = new String(responseBody);
try {
/*将这个字符串中的[]内包含的字符串以每个json对象为一个单位取下来存放在JSONArray中*/
/*此处的jsonArray里存放的元素就是原先在[]中存放着的json对象*/
JSONArray jsonArray = new JSONArray(data);
/*获取jsonArray中的第二个元素,即原来json数组[]中的第二个对象*/
JSONObject jsonObject = jsonArray.getJSONObject(1);
/*获取这个对象中的与 " " 中参数匹配的值*/
textView.setText(jsonObject.getString("catIntro"));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}

layout.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:orientation="vertical">


<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="null"

android:textColor="#000000"
android:textSize="50sp"
android:layout_gravity="center"
android:id="@+id/textView2" />


</LinearLayout>

(本文系作者原创,转载请注明出处)