android内部存储写文件格式,Android内部存储,如何正确解析JSON文本文件

我正在创建一个Android应用程序,它使用JSON对象创建一个文本文件并将其写入内部存储。我有以下代码来做到这一点:

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();

}

现在我得到一个看起来像这样的文本文件:

{"Id":"20101211T155146","Length":10}, {"Id":"20101211T155155","Length":10},

{"Id":"20101211T155203","Length":10}, {"Id":"20101211T155252","Length":10},

我现在想在JSON文件中收集这些数据。该应用程序需要编写,存储和检索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() + "]nn";

int i;

for (i=0;i

{

JSONObject post = entries.getJSONObject(i);

x += "------------n";

x += "Id:" + post.getString("Id") + "n";

x += "Length:" + post.getString("Length") + "nn";

}

它抛出一个错误。我从一个很棒的教程中获得了解析代码:http://www.ibm.com/developerworks/web/library/x-andbene1/?ca = dr -#author1

在该示例中,代码期望整个文件的括号,并且在最后一个对象之后没有逗号。所以我需要:

[{"Id":"20101211T155146","Length":10}, {"Id":"20101211T155155","Length":10},

{"Id":"20101211T155203","Length":10}, {"Id":"20101211T155252","Length":10}]

但是我在代码中一次编写了一些JSON行;如何操作JSON文本文件以获得预期的格式?

更新:

问题仍然是,如果用户将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"

}

]

如何读取第一个数组,添加第二个数据然后重新编写文件,两个数组合并为一个?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值