简体   繁体   English

Android - 如何正确编写 JSONObject 字符串

[英]Android - How to correctly write a JSONObject string

I'm trying to read/write a json file.我正在尝试读取/写入 json 文件。 But after the first write the json is escaped and reading it again doesn't work.但是在第一次写入后,json 被转义,再次读取它不起作用。 I have the following json structure but with a lot more value :我有以下 json 结构,但具有更多价值:

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

Here is how i build my json string :这是我如何构建我的 json 字符串:

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 ?如何正确构建我的 json 字符串?

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.编辑:错误来自我构建我的 json 字符串以写入文件的地方,所以我重写了我的问题。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM