How to avoid quotes in a JSON object?

Below is my method, which does JSONObjectand then prints JSONString.

I am using Google GSON.

private String generateData(ConcurrentMap<String, Map<Integer, Set<Integer>>> dataTable, int i) {

    JsonObject jsonObject = new JsonObject();

    Set<Integer> ap = dataTable.get("TEST1").get(i);
    Set<Integer> bp = dataTable.get("TEST2").get(i);

    jsonObject.addProperty("description", "test data");
    jsonObject.addProperty("ap", ap.toString());
    jsonObject.addProperty("bp", bp.toString());

    System.out.println(jsonObject.toString());

    return jsonObject.toString();
}

Currently, if I print jsonObject.toString(), then it prints like this -

{"description":"test data","ap":"[0, 1100, 4, 1096]","bp":"[1101, 3, 6, 1098]"}

But that is not what I need. I want to print, as shown below, without double quotes in the apand values bp.

{"description":"test data","ap":[0, 1100, 4, 1096],"bp":[1101, 3, 6, 1098]}

I'm not sure how to avoid these quotes in a JSONObject?

+4
source share
4 answers

Your problem is that using

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

you add a property representing the Stringview Setin Java. This has nothing to do with JSON (even if the format looks the same).

Set JsonElement (a JsonArray, ).

Gson -

Gson gson = new Gson();

, Set JsonElement JsonObject.

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

Gson , a Set JsonArray, JsonElement, JsonObject#add(String, JsonElement).

+5

, regex, ...

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

: "[ []"

JSON, , .

0

Android Platform 23, org.json.JSONObject :

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

StringEscapeUtils:

import org.apache.commons.lang3.StringEscapeUtils;

(...)

myString = StringEscapeUtils.escapeJson(myString);

On Android, be sure to update the /build.gradle app:

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

Source: https://habr.com/ru/post/1528230/


All Articles