Android JSONの簡単な処理
4223 ワード
JSON(JavaScript Object Notation)は、データ交換フォーマットです。
JSONファイルにデータを保存
/**
* crime JSON
* @param crimes
* @throws JSONException
* @throws IOException
*/
public void saveCrimes(ArrayList crimes) throws JSONException,IOException{
//Build an array in JSON
JSONArray array=new JSONArray();
for (Crime c:crimes){
array.put(c.toJSON());
}
//write a file in disk
Writer writer=null;
try{
OutputStream out=mContext.openFileOutput(mFilename,Context.MODE_PRIVATE);
writer.write(array.toString());
}finally {
if (writer!=null){
writer.close();
}
}
}
private static final String JSON_ID="id";
private static final String JSON_TITLE="title";
private static final String JSON_SOLVED="solved";
private static final String JSON_DATE="date";
...
/**
* crimes JSON
* @return
* @throws JSONException
*/
public JSONObject toJSON() throws JSONException{
JSONObject json=new JSONObject();
json.put(JSON_ID,id.toString());
json.put(JSON_TITLE,title);
json.put(JSON_SOLVED,solved);
json.put(JSON_DATE,date.getTime());
return json;
}
public boolean saveCrimes() {
try {
mSerializer.saveCrimes(mCrimes);
Log.d(TAG, "crimes save to file");
return true;
} catch (Exception e) {
Log.e(TAG, "error saving crimes", e);
return false;
}
}
@Override
public void onPause() {
super.onPause();
CrimeLab.get(getActivity()).saveCrimes();
}
ファイルからJSONデータを読み込む
/**
* crime
* @param json
* @throws JSONException
*/
public Crime(JSONObject json) throws JSONException{
id=UUID.fromString(json.getString(JSON_ID));
if (json.has(JSON_TITLE)){
title=json.getString(JSON_TITLE);
}
solved=json.getBoolean(JSON_SOLVED);
date=new Date(json.getLong(JSON_DATE));
}
/**
* crime loadCrimes()
* @return
* @throws IOException
* @throws JSONException
*/
public ArrayList loadCrimes() throws IOException,JSONException{
ArrayList crimes=new ArrayList<>();
BufferedReader reader=null;
try {
//open and read the file into a StringBuilder
InputStream in=mContext.openFileInput(mFilename);
reader=new BufferedReader(new InputStreamReader(in));
StringBuilder jsonString=new StringBuilder();
String line=null;
while ((line=reader.readLine())!=null){
//line breaks and omitted and irrelevant
jsonString.append(line);
}
//parse this JSON using JSONTokener
JSONArray array= (JSONArray) new JSONTokener(jsonString.toString()).nextValue();
//build the array of crimes from JSONObjects
for (int i = 0; i < array.length(); i++) {
crimes.add(new Crime(array.getJSONObject(i)));
}
}catch (FileNotFoundException e){
//Ignore this one,it happen when starting fresh
}finally {
if (reader!=null){
reader.close();
}
}
return crimes;
}