Reputation: 1272
I have problems saving my JSONArray , which i need for my game. I have 2 Methods :
public void saveArr(Context c,JSONArray arr,String name){
String fileName = name+"Arr.json";
String data = "";
if (arr != null) {
/*
Convert JSONArray to String
*/
data = arr.toString();
/*
TODO PROBLEM data not compatible with JSONArray
*/
}
FileOutputStream fos;
try {
fos = c.openFileOutput(fileName, Context.MODE_PRIVATE);
fos.write(data.getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
and
public JSONArray getArrJSON(Context c,String name){
StringBuilder sb =null;
JSONObject obj=null ;
JSONArray arr = null;
try {
FileInputStream fis = c.openFileInput(name+"Arr.json");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
//Here i get an Exception JSONException
obj= new JSONObject(sb.toString());
arr = deck.getJSONArray("arr");
} catch (Exception e) {
e.printStackTrace();
}
return arr;
}
The JSONArray looks like this:
[
{
"pictures":[
{
"key":"value"
}
],
"name":"name",
"id":"id"
},
{
"pictures":[
{
"key":"value"
}
],
"name":"name",
"id":"id"
}
]
I get an Exception, which i cant post, since my json file is to long... But is is a JSONException at this line :
`obj= new JSONObject(sb.toString());`
in the method getArrJSON
I dont know where my mistake begins.But i think that an error ist that :
arr = deck.getJSONArray("arr");
But like i said before the exception is thrown in the previous line.
Upvotes: 0
Views: 714
Reputation: 2740
Instead of
obj= new JSONObject(sb.toString());
try
arr = new JSONArray(sb.toString());
The string that you write to disk in the first method represents a JSONArray and not a JSONObject.
It's important to know the difference between a JSONObject and a JSONArray. A JSONArray (usually) contains JSONObjects, and a string representation of a JSONArray always start with a '['.
Upvotes: 1