安卓解析JSON

Json的数据结构

例如:

[

????{????

???????? "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的解析

SecondActivity.java

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;
@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/icampus_config.json", null, new AsyncHttpResponseHandler() {
@Override
public void onFailure(int arg0, Header[] arg1, byte[] arg2,
Throwable arg3) {
}

@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
/*
把从网址中获得的json数数据由byte数组转换为字符串格式*/
String data = new String(responseBody);
System.out.println("
这是字符串"+data);/*调试*/
try {
/*JSONArray
的构造方法就是将字符串中的数组拿出来并放到JSONArray*/
JSONArray = new JSONArray(data);
System.out.println("
这是JSON数组的第一个元素"+jsonArray.getJSONObject(0));
/*
将数组中的第一元素(第一个JSON对象提取出来,赋给一个JSONobject,这样这个JSONobject中就存放着一个json数据)*/
JSONObject = jsonArray.getJSONObject(0);
/*
通过getString方法由键名找到对应的值*/
System.out.println(jsonObject.getString("newsApi"));
textView.setText(jsonObject.getString("newsApi"));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}

?

layout.xml

<?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>

?

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。