I'm creating an Android app wh开发者_如何学Pythonich creates a text file with JSON objects and writes it to internal storage. I have the following code to do that:
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();
}
Now I get a text file which looks like so:
{"Id":"20101211T155146","Length":10}, {"Id":"20101211T155155","Length":10},
{"Id":"20101211T155203","Length":10}, {"Id":"20101211T155252","Length":10},
I'd like to now collect that data in the JSON file. The app needs to write, store and retrieve the JSON. The problem is when I go to parse the JSON objects from the file using:
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";
}
It throws an error. I got the parsing code from a great tutorial at: http://www.ibm.com/developerworks/web/library/x-andbene1/?ca=drs-#author1 In that example, the code is expecting brackets around the whole file and no comma after the last object. So I would need:
[{"Id":"20101211T155146","Length":10}, {"Id":"20101211T155155","Length":10},
{"Id":"20101211T155203","Length":10}, {"Id":"20101211T155252","Length":10}]
But I write those JSON lines one at time in my code; How can I manipulate the JSON text file to get it in the expected format?
UPDATE:
The problem is still that if the user writes the JSON array to the file and then comes back and changes it again, you get two JSON arrays in that file. Like so:
[
{
"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"
}
]
How can I read the first array, add the second and then re-write the file with both arrays merged into one?
You need to use JSONArray
to create an array of JSON objects
. Once you do a toString(), you will have the expected brackets. You do not need to manually add the commas either.
Take a look at http://developer.android.com/reference/org/json/JSONArray.html for more info
to make this a valid JSON array, you need to encapsulate the JSON-Objects (
{...}
) in braces ([]
). Thus, you could put[
into the file on creation and- either have a single point where the array is finished and you just write a closing brace
]
instead of the next comma (,
), or you do not have such a single point. Whenever you write the next object, you might be able to go back one byte in the stream via f.ex.
try { FileChannel ch = fos.getChannel(); ch.position(ch.position -1); ch.write(", ".getBytes()); ch.write(ByteBuffer.wrap(myJSONString.getBytes())); ch.write("]".getBytes()); } finally { out.close(); }
- either have a single point where the array is finished and you just write a closing brace
(concerning the "UPDATE"): Just read the whole array from the file, update it in memory (via JSONArray.put()), and overwrite the file.
To overwrite, replace the
Context.MODE_APPEND
with 0, as written in the API.It would be better if you created the array correctly. If you are given the arrays as in your update, you could search for the occurrence of
][
, split your file on that, create the JSON from both objects, and merge those (once again, via JSONArray.put()).
精彩评论