开发者社区 问答 正文

Android-JSONObject转换为字符串而不进行转义

0

我正在尝试读取/写入json文件。但是在第一次写入之后,json会转义并再次读取将不起作用。我具有以下json结构,但具有更多的价值:

{
  "events": {
    "XdQKixgtraz17eDHb6OW": {
      "department": "Côte-d'Or",
      "objectName": "Dijon",
      "uid": "PMhzfzWlm6vN2yL1kY2i"
    }
  }
}

这是我的阅读功能:

public static JSONObject readJSONFile (String path, Context context){
    try {
        File jsonFile = new File(context.getFilesDir(), path);
        FileInputStream stream = new FileInputStream(jsonFile);
        String jsonStr = null;
        try {
            FileChannel fc = stream.getChannel();
            MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());

            jsonStr = Charset.defaultCharset().decode(bb).toString();
        }
        catch(Exception e){
            e.printStackTrace();
        }
        finally {
            stream.close();
        }

        JSONObject jsonObj = new JSONObject((jsonStr));
        return jsonObj;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

这是我的写功能:

public static boolean writeFile(Context context, String fileName, String jsonString) {
    try {
        File file = new File(context.getFilesDir(), fileName);

        FileOutputStream stream = new FileOutputStream(file);
        stream.write(jsonString.getBytes());
        stream.close();

        return true;
    } catch (FileNotFoundException fileNotFound) {
        fileNotFound.printStackTrace();
        return false;
    } catch (IOException ioException) {
        ioException.printStackTrace();
        return false;
    }
}

我最后得到一个看起来像这样的字符串,我再也看不懂了..:

{"events":{"XdQKixgtraz17eDHb6OW":"{\"department\":\"Côte-d'Or\",\"objectName\":\"Dijon\",\"uid\":\"PMhzfzWlm6vN2yL1kY2i\"}"}}

由于我的json文件大约2 Mo而没有逃避,我试图不增加转义字符的大小。

我应该对原始文件进行转义,然后在每次读取时对其进行转义,还是有一种没有任何转义的方法?

谢谢你的时间。

展开
收起
垚tutu 2019-12-12 09:16:05 2483 分享 版权
阿里云 AI 助理回答

从你描述的问题来看,似乎是在写入JSON字符串到文件时出现了问题,导致原本应为JSON对象的部分被错误地转义成了字符串。在你的writeFile方法中,直接将整个JSON字符串写入了文件,这可能导致已序列化的JSON对象再次被当作普通字符串处理,尤其是在后续读取并尝试解析这个文件内容时。

要解决这个问题,你需要确保写入文件的数据结构正确无误。如果你的目标是维护一个包含多个事件的JSON文件,并且每个事件都是一个独立的对象而不是字符串,你应该直接操作JSONObject来添加数据,而不是将整个事件作为字符串嵌套。以下是修改后的写入函数示例:

import org.json.JSONObject;

public static boolean writeFile(Context context, String fileName, JSONObject eventJson) {
    try {
        File file = new File(context.getFilesDir(), fileName);
        // 先尝试读取已存在的JSON对象,如果文件不存在或为空,则初始化一个新的JSONObject
        JSONObject eventsJson = readJSONFile(fileName, context);
        if (eventsJson == null) {
            eventsJson = new JSONObject();
        }
        
        // 添加新的事件到"events"对象中,注意这里直接添加JSONObject,而非其字符串表示
        String eventId = eventJson.optString("uid"); // 假设使用uid作为事件的键
        if (eventId != null && !eventId.isEmpty()) {
            eventsJson.put(eventId, eventJson);
        } else {
            Log.e("WriteFile", "Event ID is missing or empty.");
            return false;
        }

        FileOutputStream stream = new FileOutputStream(file, false); // false表示不追加模式,会覆盖原文件
        stream.write(eventsJson.toString().getBytes());
        stream.close();

        return true;
    } catch (FileNotFoundException fileNotFound) {
        fileNotFound.printStackTrace();
        return false;
    } catch (IOException ioException) {
        ioException.printStackTrace();
        return false;
    } catch (JSONException jsonException) {
        jsonException.printStackTrace();
        return false;
    }
}

同时,确保你的readJSONFile方法能够正确处理空文件或非预期格式的文件,以避免异常。这样,在每次写入新事件时,都会直接操作JSON对象,保持数据结构的正确性,避免了不必要的转义问题。

有帮助
无帮助
AI 助理回答生成答案可能存在不准确,仅供参考
0 条回答
写回答
取消 提交回答