skip to Main Content

I use javax to create JsonObject and JsonArray from my List<String> and I have a list of Json objects that i want to put in a JsonObject through a JsonArray

    JsonArrayBuilder jsonArray = Json.createArrayBuilder(); 
    for (String Obj : listOfJsonDfObjects) 
       jsonArray.add(summaryObj);   //{"a":"b"},{"c":"d"}
   
    // this line introduces extra escaping quotes like this {""a"":""b""},{""c"":""d""}
    javax.json.JsonObject data = Json.createObjectBuilder()
       .add("data", jsonArray.build()).build();  

How to avoid these extra quotes escaping characters?
Thanks

2

Answers


  1. Using Gson

        Gson gson = new Gson();
        String json = gson.toJson(listOfJsonDfObjects);        
        //check json
        System.out.println(json);        
        json = json.replaceAll("\\", "");
        json = json.replaceAll(""\{", "{");
        json = json.replaceAll("\}"", "}");        
        //valid json now
        System.out.println(json);
    

    A more secure way (to avoid altering original data)

        //concatenate objects in list with comma
        String json = String.join(",", listOfJsonDfObjects);
        //convert to pseudo array
        json = "[" + json + "]"; 
        //convert pseudo json array to pseudo json object
        json = "{"data":" + json + "}";
        //cast to json object
        JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);                       
        System.out.println(jsonObject);
    
    Login or Signup to reply.
  2. You say you have a list of JSON objects, but you really have a list of JSON-formatted strings. To add them to a JsonArray, you need to parse each one into the JSON object model:

    public class JsonTest {
        public static void main(String[] args) {
            List<String> listOfJsonDfObjects = List.of(
                    "{"a":"b"}",
                    "{"c":"d"}"
            );
            JsonArrayBuilder jsonArray = Json.createArrayBuilder();
            for (String summaryObj : listOfJsonDfObjects) {
                JsonReader parser = Json.createReader(new StringReader(summaryObj));
                jsonArray.add(parser.readObject());
            }
    
            JsonObject data = Json.createObjectBuilder()
                    .add("data", jsonArray.build()).build();
    
            System.out.println(data); // {"data":[{"a":"b"},{"c":"d"}]}
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search