java - Android - JSONArray 上的 toString 使用双引号和反斜杠使 json 无效

标签 java android json string

<分区>

我有一个允许用户创建 JSON 的应用程序。想一想有一些房间的房子:用户添加了房间和房间内的元素。首先他说那里有多少个房间,然后用 Fragments 说那里有多少个物体。对于每个对象,我都有一个名称、一个图像和一个音频。

事实是每个房间都有一个 JSONArray,我可以看到每个对象。例如:

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

在日志中我可以看到:

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"}]}

而且很好。现在的问题是:必须将此 JSON 发送到 1. 另一个 Activity 2. 服务器。我到处都读到我必须使用 toString() 但是当我这样做时我得到一个无效的 JSON 因为该方法放置了一些双引号和一些反斜杠(行为是与首选项和文件中的写入相同。

在新的 Activity 中我得到:

["{\"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                                                                       

为什么它只发生在最后而不是每个对象?我该怎么做才能正确发送 json?我哪里错了?

更新

对于读/写数组:

在 fragment 中:

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

在 Activity 中:

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

日志返回这个:

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\"}]}"]

我还尝试将数组写入文件中,例如:

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

但都是一样的

(完全没有)解决方案

因为当我打印单个 JSONObject toString() 时,我认为(正如 ʍьђઽ૯ท 在评论中建议的那样)使用数组。我创建了一个 String[],我在其中添加了每个对象。

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

然后,在 Activity 中使 json 成为一个字符串:

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

最佳答案

之后:

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

像这样将其转换回 Json:

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

然后它应该返回正确的值。

关于java - Android - JSONArray 上的 toString 使用双引号和反斜杠使 json 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52470049/

相关文章:

java - REGEX:在 HTML 文本中添加链接

Android gradle - 使用配置文件的不同目录设置产品风格,查找所有目录而不仅仅是 1

java - 删除剩余参数

javascript - 如何构建这个json?

java - 最佳实践 : Save Empty Fields as null or omit Field Completely and Manage Missing Fields in Code?

java - 高效地向cassandra插入大量数据

java - File.renameTo() 失败,但在创建 FileOutputStream 对象后可以工作,为什么?

java - 单击按钮时,应用程序被强制关闭

android - 使用 "match_parent"将图像对齐到顶部

java - 即使我的代码按我想要的方式工作,是否有必要解决 Netbeans IDE 输出窗口中显示的错误?