Android:JSONの解析
外部のAPIとの通信を行う場合、
複数の要素を受信しようとする場合には、
XMLやJSONなどの構造化されたテキストで受信を行う必要がある。
ここではJSONでの場合を試してみる。
参考資料
「Android で JSON を使おう ~ 後編 ~」
・まず、受信したJSONを根本的に解析するのに JSONObject を使用する。
・解析されたJSONはJSONObjectとして要素がツリー上に管理されることになる。
ツリー上から要素を取得する場合には…
文字列として直下の要素のvalueを取得する場合:
getString で String を取得する。
直下の要素が単体要素でツリーのポイントになっている場合:
getJSONObject を使用して JSONObject を取得する。
直下の要素が複数要素でツリーのポイントになっている場合:
getJSONArray を使用して JSONArray を取得する。
サンプルコード
複数の要素を受信しようとする場合には、
XMLやJSONなどの構造化されたテキストで受信を行う必要がある。
ここではJSONでの場合を試してみる。
参考資料
「Android で JSON を使おう ~ 後編 ~」
・まず、受信したJSONを根本的に解析するのに JSONObject を使用する。
・解析されたJSONはJSONObjectとして要素がツリー上に管理されることになる。
ツリー上から要素を取得する場合には…
文字列として直下の要素のvalueを取得する場合:
getString で String を取得する。
直下の要素が単体要素でツリーのポイントになっている場合:
getJSONObject を使用して JSONObject を取得する。
直下の要素が複数要素でツリーのポイントになっている場合:
getJSONArray を使用して JSONArray を取得する。
サンプルコード
package com.tomonobu.application.test_3;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Test_program_3Activity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
setContentView(tv);
String str = "" +
"{\"count\":1,\"value\":" +
"{\"title\":\"translation_e2j\",\"description\":\"Pipes Output\"," +
"\"link\":\"http://pipes.yahoo.com/pipes/pipe.info?_id=GghNyeXA3RGVg7C01JzWFw\"," +
"\"pubDate\":\"Thu, 14 Jul 2011 20:34:32 -0700\"," +
"\"generator\":\"http://pipes.yahoo.com/pipes/\"," +
"\"callback\":\"\"," +
"\"items\":[" +
"{\"input\":\"test\"," +
"\"output\":\"\u30c6\u30b9\u30c8\"," +
"\"description\":\"\"," +
"\"title\":\"\"}" +
"]}}";
String str2 = "";
try {
int i;
JSONObject json = new JSONObject(str);
JSONObject value = json.getJSONObject("value");
JSONArray items = value.getJSONArray("items");
for (i=0; i < items.length(); i++) {
JSONObject item = items.getJSONObject(i);
str2 += item.getString("output");
}
} catch (JSONException e) {
e.printStackTrace();
}
tv.setText(str + "¥n¥n" + str2);
}
}
by Tomonobu1979
| 2011-07-15 13:34
| 未分類