How to escape the quotes in JSON Object?

后端 未结 4 1468
予麋鹿
予麋鹿 2021-01-19 17:31

Below is my method which makes the JSONObject and then print out the JSONString.

I am using Google GSON.

private String gen         


        
4条回答
  •  攒了一身酷
    2021-01-19 18:20

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

提交回复
热议问题