Docomo APIの音声出力は、Jsonファイルとして返される。それをJavaで構文解析をする。使わせていただいたのは、以下のサイトにあるパーサー。
https://www.tutorialspoint.com/json/json_java_example.htm
要領とサンプルを掲載しておく。
(1)サイトから、ソースをダウンロードし、ライブラリ用のjarファイルを作成する。JsonSimple.jar
(2)以下のソースのライブラリに加える。jsonと配列の処理が頭の中でごちゃごちゃになる。(なお、上記サイトのデコードサンプルは、そのままではエラーになる。なんでそんなものを?)
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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import org.json.simple.JSONObject; import org.json.simple.JSONArray; import org.json.simple.parser.ParseException; import org.json.simple.parser.JSONParser; public class JsonParserTest { String readJsonFile() { // 出力結果をファイルから読み込む場合 // 通常は、httpレスポンスをそのまま、次のparseJasonで解析すれば良い String json = "" ; try { File file = new File( "/path/to/docomo_output.json" ); BufferedReader br = new BufferedReader( new FileReader(file)); String str; while ((str = br.readLine()) != null ) { json += str; } br.close(); } catch (FileNotFoundException e) { System.out.println(e); } catch (IOException e) { System.out.println(e); } return json; } void parseJson(String json) { JSONParser parser = new JSONParser(); try { JSONObject obj0 = (JSONObject )parser.parse(json); //認識テキストの出力 //出力テキストの全体は、textタグを読み取れば良い System.out.println( "出力テキスト" ); System.out.println(obj0.get( "text" )); // 以上で良いのだが、分かち書きされた分析結果も受け取るようにして見る // resultの値は、配列になっているので、まずその配列を受け取る JSONArray results_array = (JSONArray) obj0.get( "results" ); // 配列の最初の要素を取り出す JSONObject obj1_tokens = (JSONObject )results_array.get( 0 ); // 配列の最初の要素が"tokens"というJsonになっているので、それをうけとる // そのtokensの値が配列になっているので、配列として受け取る JSONArray array1_tokens = (JSONArray) (obj1_tokens.get( "tokens" )); // tokensの配列をループにして回す for (Object ob : array1_tokens) { JSONObject job = (JSONObject) ob; String written = (String) job.get( "written" ); System.out.print( "書き方:" + written + "," ); double confidence = ( double ) job.get( "confidence" ); System.out.print( "信頼性:" + confidence + "," ); String spoken = (String) job.get( "spoken" ); System.out.println( "読み:" + spoken); // 他の要素は省略 } } catch (ParseException pe) { System.out.println( "position: " + pe.getPosition()); System.out.println(pe); } } public static void main(String[] args) { JsonParserTest jparser = new JsonParserTest(); jparser.parseJson(jparser.readJsonFile()); } } |