logo

JavaでJSONを解析する方法

JSON (JavaScript Object Notation) は、人間や機械が簡単に読み書きできる、軽量でテキストベースの言語に依存しないデータ交換形式です。 JSON は、オブジェクトと配列という 2 つの構造化タイプを表すことができます。オブジェクトは、0 個以上の名前と値のペアの順序付けされていないコレクションです。配列は、0 個以上の値の順序付けされたシーケンスです。値には、文字列、数値、ブール値、null、およびこれら 2 つの構造化タイプを使用できます。

以下は、人を説明するオブジェクトの JSON 表現を示す Wikipedia の簡単な例です。このオブジェクトには、姓名を表す文字列値、年齢を表す数値、個人の住所を表すオブジェクト値、および電話番号オブジェクトの配列値が含まれます。



 { 'firstName': 'John', 'lastName': 'Smith', 'age': 25, 'address': { 'streetAddress': '21 2nd Street', 'city': 'New York', 'state': 'NY', 'postalCode': 10021 }, 'phoneNumbers': [ { 'type': 'home', 'number': '212 555-1234' }, { 'type': 'fax', 'number': '646 555-4567' } ] }>

Java での JSON 処理: JSON 処理用の Java API JSON.simple は、JSON を解析、生成、変換、クエリできるシンプルな Java ライブラリです。

はじめる : ダウンロードする必要があります json-simple-1.1 jar 以下のサンプルコードをコンパイルして実行する前に、それを CLASSPATH に配置してください。

Json シンプル API : JSON オブジェクトと配列構造のオブジェクト モデルを提供します。これらの JSON 構造は、型を使用してオブジェクト モデルとして表現されます。 JSONオブジェクト そして JSON配列 。 JSONObject が提供するのは、 地図 ビューを使用して、モデルから 0 個以上の名前と値のペアの順序なしコレクションにアクセスします。同様に、JSONArray は リスト ビューを使用して、モデルから 0 個以上の値の順序付けられたシーケンスにアクセスします。



JSONをファイルに書き込む

JSONObject と JSONArray を使用して、上記の JSON データをファイル JSONExample.json に書き込む例を見てみましょう。






標準Cプログラミング

// Java program for write JSON to a file> > import> java.io.FileNotFoundException;> import> java.io.PrintWriter;> import> java.util.LinkedHashMap;> import> java.util.Map;> import> org.json.simple.JSONArray;> import> org.json.simple.JSONObject;> > public> class> JSONWriteExample> {> >public> static> void> main(String[] args)>throws> FileNotFoundException> >{> >// creating JSONObject> >JSONObject jo =>new> JSONObject();> > >// putting data to JSONObject> >jo.put(>'firstName'>,>'John'>);> >jo.put(>'lastName'>,>'Smith'>);> >jo.put(>'age'>,>25>);> > >// for address data, first create LinkedHashMap> >Map m =>new> LinkedHashMap(>4>);> >m.put(>'streetAddress'>,>'21 2nd Street'>);> >m.put(>'city'>,>'New York'>);> >m.put(>'state'>,>'NY'>);> >m.put(>'postalCode'>,>10021>);> > >// putting address to JSONObject> >jo.put(>'address'>, m);> > >// for phone numbers, first create JSONArray> >JSONArray ja =>new> JSONArray();> > >m =>new> LinkedHashMap(>2>);> >m.put(>'type'>,>'home'>);> >m.put(>'number'>,>'212 555-1234'>);> > >// adding map to list> >ja.add(m);> > >m =>new> LinkedHashMap(>2>);> >m.put(>'type'>,>'fax'>);> >m.put(>'number'>,>'212 555-1234'>);> > >// adding map to list> >ja.add(m);> > >// putting phoneNumbers to JSONObject> >jo.put(>'phoneNumbers'>, ja);> > >// writing JSON to file:'JSONExample.json' in cwd> >PrintWriter pw =>new> PrintWriter(>'JSONExample.json'>);> >pw.write(jo.toJSONString());> > >pw.flush();> >pw.close();> >}> }>

>

>

ファイル JSONExample.json からの出力:

 { 'lastName':'Smith', 'address':{ 'streetAddress':'21 2nd Street', 'city':'New York', 'state':'NY', 'postalCode':10021 }, 'age':25, 'phoneNumbers':[ { 'type':'home', 'number':'212 555-1234' }, { 'type':'fax', 'number':'212 555-1234' } ], 'firstName':'John' }>

注記 : JSON では、オブジェクトは順序のない名前と値のペアのセットであるため、(定義上) 重要ではないため、JSONObject はオブジェクトの名前と値のペアの順序を保持しません。したがって、出力ファイルでは順序が保持されません。

ファイルから JSON を読み取る

JSONParser、JSONObject、および JSONArray を使用して、上記で作成されたファイル JSONExample.json から JSON データを読み取る例を見てみましょう。




// Java program to read JSON from a file> > import> java.io.FileReader;> import> java.util.Iterator;> import> java.util.Map;> > import> org.json.simple.JSONArray;> import> org.json.simple.JSONObject;> import> org.json.simple.parser.*;> > public> class> JSONReadExample> {> >public> static> void> main(String[] args)>throws> Exception> >{> >// parsing file 'JSONExample.json'> >Object obj =>new> JSONParser().parse(>new> FileReader(>'JSONExample.json'>));> > >// typecasting obj to JSONObject> >JSONObject jo = (JSONObject) obj;> > >// getting firstName and lastName> >String firstName = (String) jo.get(>'firstName'>);> >String lastName = (String) jo.get(>'lastName'>);> > >System.out.println(firstName);> >System.out.println(lastName);> > >// getting age> >long> age = (>long>) jo.get(>'age'>);> >System.out.println(age);> > >// getting address> >Map address = ((Map)jo.get(>'address'>));> > >// iterating address Map> >Iterator itr1 = address.entrySet().iterator();> >while> (itr1.hasNext()) {> >Map.Entry pair = itr1.next();> >System.out.println(pair.getKey() +>' : '> + pair.getValue());> >}> > >// getting phoneNumbers> >JSONArray ja = (JSONArray) jo.get(>'phoneNumbers'>);> > >// iterating phoneNumbers> >Iterator itr2 = ja.iterator();> > >while> (itr2.hasNext())> >{> >itr1 = ((Map) itr2.next()).entrySet().iterator();> >while> (itr1.hasNext()) {> >Map.Entry pair = itr1.next();> >System.out.println(pair.getKey() +>' : '> + pair.getValue());> >}> >}> >}> }>

Java仮想マシン
>

>

出力:

 John Smith 25 streetAddress : 21 2nd Street postalCode : 10021 state : NY city : New York number : 212 555-1234 type : home number : 212 555-1234 type : fax>