2011年12月1日木曜日

[AndroidSDK]JSONの書き込み

JSONを使用すると、アプリの細かな情報を簡単にストレージに保存できる
iPhoneでいうところplist的な扱いができる
やたらソース長いので短くしたいところ

//ファイルの有無を確認
FileInputStream fileInputStream;
JSONObject jsono = null;
try {
    fileInputStream = openFileInput("profile.json");
    int size = fileInputStream.available();
    byte[] buffer = new byte[size];
    fileInputStream.read(buffer);
    fileInputStream.close();
    String jsnoString = new String(buffer);
    jsono = new JSONObject(jsnoString);
   
} catch (FileNotFoundException e) {
    log("FileNotFoundException "+e);
    //ファイルが存在しないので作成する
    try {
        jsono = new JSONObject();
        jsono.put("hogeInt", 2);
        jsono.put("hogeBool", false);
        jsono.put("hogeString", "foo");
       
        try {
            //ファイルを書き込む
            FileOutputStream fileOutputStream;
            fileOutputStream = openFileOutput("profile.json", MODE_PRIVATE);
            String value = jsono.toString();
            fileOutputStream.write(value.getBytes());
            fileOutputStream.close();
           
        } catch (FileNotFoundException e1) {
            log("FileNotFoundException "+e1);
           
        } catch (IOException e1) {
            log("IOException "+e1);
        }
       
    } catch (JSONException e1) {
        log("JSONException "+e1);
    }
} catch (IOException e) {
    log("JSONException "+e);
   
} catch (JSONException e) {
    log("IOException "+e);
}

try {
    jsono.put("hogeBool", true);
} catch (JSONException e1) {
    log("JSONException "+e1);
}

//ファイルを書き込む
try {
    FileOutputStream fileOutputStream;
    fileOutputStream = openFileOutput("profile.json", MODE_PRIVATE);
    fileOutputStream.write(jsono.toString().getBytes());
    fileOutputStream.close();
   
} catch (FileNotFoundException e1) {
    log("FileNotFoundException "+e1);
   
} catch (IOException e1) {
    log("IOException "+e1);
}

0 件のコメント:

コメントを投稿