I'm trying to read/write a json file. But after the first write the json is escaped and reading it again doesn't work. I have the following json structure but with a lot more value :
{
"events": {
"XdQKixgtraz17eDHb6OW": {
"department": "Côte-d'Or",
"objectName": "Dijon",
"uid": "PMhzfzWlm6vN2yL1kY2i"
}
}
}
Here is how i build my json string :
JSONObject eventsJsonObject = new JSONObject();
JSONObject eventsData = new JSONObject();
for(Event event: eventsList){
String eventString = gson.toJson(event);
eventsData.put(event.getUid(), eventString);
}
eventsJsonObject.put("events", eventsData);
writeFile(filename, eventsJsonObject.toString());
I end up with a string looking like this and i can't read it again .. :
{"events":{"XdQKixgtraz17eDHb6OW":"{\"department\":\"Côte-d'Or\",\"objectName\":\"Dijon\",\"uid\":\"PMhzfzWlm6vN2yL1kY2i\"}"}}
As you can see there is a quote before the third semi colon that shouldn't be there. How can i correctly build my json string ?
Thanks for your time.
Edit : The error came from where i build my json string to write in file so i have rewrite my question.
Try this code
public static JSONObject readJSONFile (String path, Context context) {
String jsonStr = null;
try {
InputStream is = getActivity().getAssets().open(path);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
jsonStr = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
JSONObject jsonObj = new JSONObject((jsonStr ));
return jsonObj;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.