How to escape the quotes in JSON Object?

那年仲夏 提交于 2019-12-01 19:01:37

Your problem is that with

jsonObject.addProperty("ap", ap.toString());

you are adding a property which is the String representation of a Set in Java. It has nothing to do with JSON (even if the format looks the same).

You will have to convert your Set into a JsonElement (a JsonArray really but you won't see that).

Create a Gson object somewhere

Gson gson = new Gson();

and use it to convert your Set elements to JsonElement objects and add them to the JsonObject.

jsonObject.add("ap", gson.toJsonTree(ap));
jsonObject.add("bp", gson.toJsonTree(bp));

Gson has its conventions, it converts a Set into a JsonArray which is a sub type of JsonElement and you can therefore add it with JsonObject#add(String, JsonElement).

Use StringEscapeUtils:

import org.apache.commons.lang3.StringEscapeUtils;

(...)

myString = StringEscapeUtils.escapeJson(myString);

On Android, remember to update your app/build.gradle:

compile 'org.apache.commons:commons-lang3:3.4'

Maybe try regex if you really need a string...

string.replace(new RegExp('("\\[)', 'g'), '[').replace(new RegExp('(\\]")', 'g'), ']')

Better explained, "[ is replaced with [ and ]" is replaced with ]

Question was not his method of working with the JSON Object, it was how to escape array quotes.

If you are using Android Platform 23 then you shall able to use org.json.JSONObject instead:

private String generateData(ConcurrentMap<String, Map<Integer, Set<Integer>>> dataTable, int i) {
JSONObject jsonObject = new JSONObject();
try {
    JSONArray apArray = new JSONArray();
    for (Integer i : ap) {
        apArray.put(i.intValue());
    }
    JSONArray bpArray = new JSONArray();
    for (Integer i : bp) {
        bpArray.put(i.intValue());
    }

    jsonObject.put("description", "test data");

    jsonObject.put("ap", apArray);
    jsonObject.put("bp", bpArray);
    Log.d("Json string", jsonObject.toString());
}catch(JSONException e){
    Log.e("JSONException",e.getMessage());
}

System.out.println(jsonObject.toString());
return jsonObject.toString();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!