1

I have an app that let users create a JSON. Think about a house with some rooms: the user adds the rooms and the objects inside them. First he says how many rooms are there, then, with Fragments, says how many objects are in there. For every object I have a name, an image and an audio.

The fact is that I have a JSONArray with every room, and I can see every objects. E.g.:

for (int j = 0; j < lastArray.length(); j++) {
    try {
        Log.d(TAGADD, "item inserted: " + lastArray.get(j).toString());
    } catch (JSONException e) {
        Log.d(TAGADD, "errorjson: " + e.toString());
    }
}

In the log I can see this:

item inserted: {"title":"room1","image":"2015-12-02-191546_241x190_scrot.png","audio":"","items":[{"title":"obj1","image":"2015-12-02-191615_207x185_scrot.png","audio":"recording1537733679498.mp3"}]}
item inserted: {"title":"room2","image":"16366","audio":"","items":[{"title":"obj2","image":"2015-12-02-191625_222x200_scrot.png","audio":"recording1537733694671.mp3"}]}

And it's fine. Now the problems: this JSON must be send to 1. another activity 2. a server. I read everywhere that I've to use toString() but when I do it I get an invalid JSON because the method puts some double quotes and some backslashes (the behavior is identical both with the preferences and with the writing in a file).

In the new Activity I get:

["{\"title\":\"room1\",\"image\":\"2015-12-02-191546_241x190_scrot.png\",\"audio\":\"\",\"items\":[{\"title\":\"obj1\",\"image\":\"2015-12-02-191615_207x185_scrot.png\",\"audio\":\"recording1537733679498.mp3\"}]}","{\"title\":\"room2\",\"image\":\"16366\",\"audio\":\"\",\"items\":[{\"title\":\"obj2\",\"image\":\"2015-12-02-191625_222x200_scrot.png\",\"audio\":\"recording1537733694671.mp3\"}]}"]}
 ^this is a problem (there is one also at the end)                    ^these are problems                                                                       

Why does it only happen at the end and not with every object? What can I do to send the json correctly? Where am I wrong?

UPDATE

For read/write array:

In fragments:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor edit = prefs.edit();
edit.putString("fullArray", lastArray.toString());
edit.apply();

In Activity:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String arr = prefs.getString("fullArray", null);
Log.d("aftroomadd","read arr: "+arr);

The log returns this:

read arr: ["{\"title\":\"r1\",\"image\":\"2015-12-02-191546_241x190_scrot.png\",\"audio\":\"\",\"items\":[{\"title\":\"o1\",\"image\":\"2015-12-02-191615_207x185_scrot.png\",\"audio\":\"AUD-20180828-WA0011.mp3\"}]}","{\"title\":\"r2\",\"image\":\"16366\",\"audio\":\"\",\"items\":[{\"title\":\"o2\",\"image\":\"2015-12-02-191625_222x200_scrot.png\",\"audio\":\"AUD-20180828-WA0012.mp3\"}]}"]

I also tried to write the array in a file like:

public static synchronized void saveToFileSystem(Context context, Object object, String binFileName) {
    try {
        String tempPath = context.getFilesDir() + "/" + binFileName;
        File file = new File(tempPath);
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
        oos.writeObject(object);
        oos.flush();
        oos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

saveToFileSystem(getContext(),fullEx.toString(),"tempFileJson");

But it's the same.

(Not at all) Solution

Since when I print the individual JSONObject the toString() works correctly, I thought (as ʍѳђઽ૯ท suggests in a comment) to use an array. I create a String[] in which I add every single object.

In fragment:

String[] a = new String[lastArray.length()];
for (int j = 0; j < lastArray.length(); j++) {
    try {
        a[j]= lastArray.get(j).toString();
    } 
    catch (JSONException e) {
        Log.d(TAGADD, "errorjson: " + e.toString());
    }
 }
 getActivity().getFragmentManager().popBackStack();
 Intent i = new Intent(getActivity(), UploadExActivity.class);
 i.putExtra("jsonArray", a);
 startActivity(i);

Then, in the Activity to make the json a single string:

Intent intent = getIntent();
String[] arr = intent.getStringArrayExtra("jsonArray");
String t, full;
StringBuilder builder = new StringBuilder();
int size = arr.length;
int i=0;
for(String s : arr) {
    Log.d("aftroomadd", "read arr: " +s);
    builder.append(s);
    if(size-i>1)
        builder.append(",");
    i++;
}

t= builder.toString();

full = "[" + t + "]";
Log.d("aftroomadd", "final json in string: "+full);
tuzzo
  • 75
  • 1
  • 1
  • 10
  • 1
    Please paste the codes which you sent-read from another `Activity`. Anyways, `toString()` just converts the data to String and I don't think that might be the issue in here. – ʍѳђઽ૯ท Sep 23 '18 at 20:41
  • @ʍѳђઽ૯ท added. Note that in the loop the individual objects are correct – tuzzo Sep 24 '18 at 00:27

1 Answers1

1

After:

String arr = prefs.getString("fullArray", null);

Convert it back to Json like this:

String arr = prefs.getString("fullArray", null);
JsonObject jsonObject = new JsonObject(arr); // Or new JsonArray or whatever json is
Log.d("My converted Json" + jsonObject);

And then it should return the right value.

ʍѳђઽ૯ท
  • 16,646
  • 7
  • 53
  • 108
  • I tried `new JSONArray(arr)` and I still get `["{\"title\":\"r1\" //and so on` – tuzzo Sep 24 '18 at 10:12
  • SharedPreferences is ideal for small data and not a json output like that so that might be the issue. However, I’d save it in an Array or check this question; https://stackoverflow.com/questions/33208205/how-to-store-json-object-to-shared-preferences – ʍѳђઽ૯ท Sep 24 '18 at 11:04
  • As I said in the question, I've already tried with a file. Anyway I saved every JSONObjects in a `String[]` and it seems that it works (for now). If no other problems appear, I set your answer as the best since I follow your array tip – tuzzo Sep 25 '18 at 19:57