JSONからjavaにデータを読み込む方法
前回挫折したけど再度挑戦
日本語PublicTweetにはアイコンの画像データが配信されていないためにJSONで取得に切り替え
JSONICは使い方わからなかったので、別の物を使ってみる
- FlaCode: del.icio.usをJSONのAPIを通してJavaから利用する
できたけど処理速度がいまいち
contentsの取得方法に無駄があった
こんな感じに修正
URL url = new URL("http://pcod.no-ip.org/yats/public_timeline?json"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); String contents =IOUtils.toString(reader);
悔しいからJSONICの方も挑戦
二次元配列で取得はできたけど、リストの処理の詳細がわからないので諦め
import org.json.JSONArray;
import org.json.JSONObject;
この2つ使うとこんなに綺麗に書けた
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URL; import net.arnx.jsonic.JSONException; import org.apache.commons.io.IOUtils; import org.json.JSONArray; import org.json.JSONObject; public class getTweetFromJSON { public static void main(String[] args) throws org.json.JSONException, UnsupportedEncodingException, IOException { URL url = new URL("http://pcod.no-ip.org/yats/public_timeline?json"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); String contents =IOUtils.toString(reader); try { JSONArray ja = new JSONArray(contents); for (int i = 0; i < ja.length(); i++) { JSONObject jo = (JSONObject) ja.get(i); System.out.println(i); System.out.println(jo.getString("url")); System.out.println(jo.getString("content")); System.out.println(jo.getString("id")); System.out.println(jo.getString("image")); System.out.println(jo.getString("user")); System.out.println(jo.getString("time")); System.out.println(); } } catch (JSONException e) { e.printStackTrace(); } } }
これだとただ標準出力してるだけだから、DBに追加するように修正して完成
とりあえず完成
テスト稼働開始
初めてSeasarのプロダクトを使ってプログラムをを動かしたのに感無量(Webじゃないけどw