Android-json-parser
Android-JSONパーサー
JSONはJavaScript Object Notationの略で、独立したデータ交換形式であり、XMLの最適な代替手段です。 この章では、JSONファイルを解析し、必要な情報を抽出する方法について説明します。
Androidには、JSONデータを操作するための4つの異なるクラスが用意されています。 これらのクラスは、 JSONArray、JSONObject、JSONStringer、およびJSONTokenizer です。
最初のステップは、関心のあるJSONデータのフィールドを識別することです。 例えば。 下記のJSONでは、温度のみを取得することに興味があります。
{
"sys":
{
"country":"GB",
"sunrise":1381107633,
"sunset":1381149604
},
"weather":[
{
"id":711,
"main":"Smoke",
"description":"smoke",
"icon":"50n"
}
],
"main":
{
"temp":304.15,
"pressure":1009,
}
}
JSON-要素
JSONファイルは多くのコンポーネントで構成されています。 JSONファイルのコンポーネントとその説明を定義する表は次のとおりです-
| Sr.No | Component & description |
|---|---|
| 1 |
Array([) JSONファイルでは、角括弧([)はJSON配列を表します |
| 2 |
Objects(\{) JSONファイルでは、中括弧(\ {)はJSONオブジェクトを表します |
| 3 |
Key JSONオブジェクトには、単なる文字列であるキーが含まれています。 キー/値のペアがJSONオブジェクトを構成します |
| 4 |
Value 各キーには、string、integer、またはdouble e.t.cの値があります |
JSON-解析
JSONオブジェクトを解析するには、クラスJSONObjectのオブジェクトを作成し、それにJSONデータを含む文字列を指定します。 その構文は-
String in;
JSONObject reader = new JSONObject(in);
最後のステップは、JSONを解析することです。 JSONファイルは、異なるキー/値ペアe.t.cを持つ異なるオブジェクトで構成されます。 そのため、JSONObjectには、JSONファイルの各コンポーネントを解析するための個別の関数があります。 その構文は以下のとおりです-
JSONObject sys = reader.getJSONObject("sys");
country = sys.getString("country");
JSONObject main = reader.getJSONObject("main");
temperature = main.getString("temp");
メソッド getJSONObject はJSONオブジェクトを返します。 メソッド getString は、指定されたキーの文字列値を返します。
これらのメソッドとは別に、JSONファイルをより適切に解析するために、このクラスによって提供される他のメソッドがあります。 これらの方法は以下のとおりです-
| Sr.No | Method & description |
|---|---|
| 1 |
get(String name) このメソッドは値を返すだけですが、オブジェクト型の形式で |
| 2 |
getBoolean(String name) このメソッドは、キーで指定されたブール値を返します |
| 3 |
getDouble(String name) このメソッドは、キーで指定されたdouble値を返します |
| 4 |
getInt(String name) このメソッドは、キーで指定された整数値を返します |
| 5 |
getLong(String name) このメソッドは、キーで指定されたlong値を返します |
| 6 |
length() このメソッドは、このオブジェクトの名前/値マッピングの数を返します。 |
| 7 |
names() このメソッドは、このオブジェクト内の文字列名を含む配列を返します。 |
例
この例を試すには、実際のデバイスまたはエミュレーターでこれを実行できます。
| Steps | Description |
|---|---|
| 1 | You will use Android studio to create an Android application. |
| 2 | Modify src/MainActivity.java file to add necessary code. |
| 3 | Modify the res/layout/activity_main to add respective XML components |
| 4 | Modify the res/values/string.xml to add necessary string components |
| 5 | Run the application and choose a running android device and install the application on it and verify the results |
以下は、変更されたメインアクティビティファイル src/MainActivity.java の内容です。
package com.example.finddevguides7.myapplication;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ListView lv;
ArrayList<HashMap<String, String>> contactList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(MainActivity.this,"Json Data is
downloading",Toast.LENGTH_LONG).show();
}
@Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
//Making a request to url and getting response
String url = "http://api.androidhive.info/contacts/";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
//Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("contacts");
//looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
//Phone node is JSON Object
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");
//tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
//adding each child node to HashMap key => value
contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
contact.put("mobile", mobile);
//adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, contactList,
R.layout.list_item, new String[]{ "email","mobile"},
new int[]{R.id.email, R.id.mobile});
lv.setAdapter(adapter);
}
}
}
以下は、xml HttpHandler.java の変更されたコンテンツです。
package com.example.finddevguides7.myapplication;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
//read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
以下は、xml res/layout/activity_main.xml の変更されたコンテンツです。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.finddevguides7.myapplication.MainActivity">
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
以下は、xml res/layout/list_item.xml の変更されたコンテンツです。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="@dimen/activity_horizontal_margin">
<TextView
android:id="@+id/email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="@color/colorAccent"/>
<TextView
android:id="@+id/mobile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold"/>
</LinearLayout>
以下は AndroidManifest.xml ファイルの内容です。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.finddevguides7.myapplication">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
変更したばかりのアプリケーションを実行してみましょう。 環境設定中に AVD を作成したと思います。 Androidスタジオからアプリを実行するには、プロジェクトのアクティビティファイルの1つを開き、ツールバーの[画像の実行:/android/images/eclipse_run.png [Eclipse Run Icon]アイコンをクリックします。 AndroidスタジオはAVDにアプリをインストールして起動し、セットアップとアプリケーションで問題がなければ、次のエミュレータウィンドウが表示されます-
文字列jsonのデータを示す上記の例では、データには雇用者の詳細と給与情報が含まれています。