如何删除通过Javax创建的JsonObject的多余转义引号字符

4urapxun  于 2023-02-17  发布在  Java
关注(0)|答案(2)|浏览(130)

我使用javax从我的List<String>创建JsonObjectJsonArray,并且我有一个Json对象列表,我希望将这些对象放入JsonObjectJsonArray

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

如何避免这些额外的引号转义字符?谢谢

ecbunoof

ecbunoof1#

你说你有一个JSON对象列表,但实际上你有一个JSON格式的字符串列表,要将它们添加到JsonArray中,你需要将每个字符串解析到JSON对象模型中:

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"}]}
    }
}
pzfprimi

pzfprimi2#

使用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);

更安全的方法(避免更改原始数据)

//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);

相关问题