내가 JSON 개체를 사용하여 텍스트 파일을 만들고 내부 저장 장치에 기록 안드로이드 응용 프로그램을 만드는거야을 구문 분석하는 방법에 대해 설명합니다. 나는 이제 JSON 파일에서 데이터를 수집하고 싶습니다안드로이드 내부 저장, 제대로 JSON 텍스트 파일
{"Id":"20101211T155146","Length":10}, {"Id":"20101211T155155","Length":10},
{"Id":"20101211T155203","Length":10}, {"Id":"20101211T155252","Length":10},
:
JSONObject myJSON = new JSONObject();
//Set the JSON object with website, length and Id (time-stamp)
try {
myJSON.put("Length", trim)
.put("Website", data)
.put("Id", tx);
} catch (JSONException e1) {
e1.printStackTrace();
}
//Convert JSON object to a string and add a comma
String myJSONString = myJSON.toString();
myJSONString += ", ";
try {
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_APPEND);
fos.write(myJSONString.getBytes());
fos.close();
//Log.d(TAG, "Written to file");
} catch (Exception e) {
Log.d(TAG, "cought");
e.printStackTrace();
}
지금 내가 지금과 같은 텍스트 파일을 얻을 : 나는 그것을 할 수있는 다음과 같은 코드가 있습니다. 앱은 JSON을 작성, 저장 및 검색해야합니다. 문제는 파일에서 JSON 객체를 구문 분석 할 때입니다.
String x = "";
InputStream is = this.getResources().openRawResource(R.raw.pwh);
byte [] buffer = new byte[is.available()];
while (is.read(buffer) != -1);
String jsontext = new String(buffer);
JSONArray entries = new JSONArray(jsontext);
x = "JSON parsed.\nThere are [" + entries.length() + "]\n\n";
int i;
for (i=0;i<entries.length();i++)
{
JSONObject post = entries.getJSONObject(i);
x += "------------\n";
x += "Id:" + post.getString("Id") + "\n";
x += "Length:" + post.getString("Length") + "\n\n";
}
오류가 발생합니다. 나는에서 좋은 튜토리얼에서 구문 분석 코드를 가지고 : 그 예에서 http://www.ibm.com/developerworks/web/library/x-andbene1/?ca=drs-#author1 코드는 전체 파일 주위에 괄호 마지막 객체 후 아무 쉼표를 기대하고있다. 그래서 내가 필요합니다 :
[{"Id":"20101211T155146","Length":10}, {"Id":"20101211T155155","Length":10},
{"Id":"20101211T155203","Length":10}, {"Id":"20101211T155252","Length":10}]
하지만 난 내 코드에서 한 번에 그 JSON 라인을 써주세요; 예상 된 형식으로 JSON 텍스트 파일을 조작하려면 어떻게해야합니까?
UPDATE :
문제는 사용자가 돌아 오면 다시 변경 한 다음 파일로 JSON 배열을 쓰고있는 경우, 해당 파일에 이 JSON 배열를 얻을 아직도있다. 그래서 같이 :
[
{
"phonenumber": "15555215554",
"time": "20110113T173835",
"username": "edit username",
"email": " edit email",
"password": "edit password"
}
][
{
"phonenumber": "15555215554",
"time": "20110113T173900",
"username": "edit username",
"email": " edit email",
"password": "edit password"
},
{
"phonenumber": "15555215554",
"time": "20110113T173900",
"username": "edit username",
"email": " edit email",
"password": "edit password"
}
]
가 어떻게 첫 번째 배열을 읽을 수있는 두 번째를 추가 한 다음 하나에 병합 두 배열을 사용하여 파일을 다시 쓰기?
업데이트를 참조하십시오. – Chris