如何返回正确的格式JsonString

时间:2017-04-20 07:49:21

标签: java json

static String Q2(String json1, String json2, String json3){
    // given three JSON Strings, combine them into a single JSON String.
    //
    // The inputs are in the format:
    // json1: {"number":9}
    // json2: [10,14,0,12] <-- any number of ints
    // json3: [{"key1":4},{"key2":5}] <-- always 2 objects
    //
    // and the output must be in the format:
    // {"number":9,"array":[10,14,0,12],"key1":4,"key2":5}

    JsonObject array = new JsonObject();
    array.add("array", json2);

    JsonArray ans = new JsonArray();
    ans.add(json1);
    ans.add(array);
    ans.add(json3);

    String data = ans.toString();
    String formatted = data.replaceAll("\\\\", "");

    return formatted;
}

在作业分级员上面写着:

Incorrect on input: [{"number":9}, [10,14,0,12], [{"key1":4},{"key2":5}]]
Expected output : {"number":9,"array":[10,14,0,12],"key1":4,"key2":5}
Your output     : "{"number":9}",{"array":"[10,14,0,12]"},"[{"key1":4},{"key2":5}]"

我在输出和预期输出之间看到的唯一区别是括号,大括号和引号。如何删除不需要的特定内容?

2 个答案:

答案 0 :(得分:0)

首先我建议你阅读一下你的意见:

JsonReader reader1 = Json.createReader(new StringReader(json1));
JsonReader reader2 = Json.createReader(new StringReader(json2));
JsonReader reader3 = Json.createReader(new StringReader(json3));

然后将其转换为您的对象:

// The inputs are in the format:
// json1: {"number":9}
// json2: [10,14,0,12] <-- any number of ints
// json3: [{"key1":4},{"key2":5}] <-- always 2 objects

JsonObject read1 = reader1.readObject();
JsonArray read2 = reader2.readArray();
JsonArray read3 = reader3.readArray();

然后创建一个JsonObjectBuilder并将所有内容合并到其中:

JsonObjectBuilder obj = Json.createObjectBuilder();

read1.forEach((a,b) -> { 
  obj.add(a, b);
} );

obj.add("array", read2);

read3.forEach(v -> { 
  ((JsonObject)v).forEach((key,value) -> obj.add(key, value));
});

System.out.println(obj.build().toString());

打印:

{"number":9,"array":[10,14,0,12],"key1":4,"key2":5}

答案 1 :(得分:0)

我没有尝试过,但我会做这样的事情。

    //with jackson
    ObjectMapper mapper = new ObjectMapper();
    JsonNode j1 = mapper.readTree(json1);
    //HINT: I'm not sure if json array without root {} is a valid json, but this should work -> String[] sortings = mapper.readValue(json2,TypeFactory.defaultInstance().constructArrayType(String.class));
    JsonNode j2 = mapper.readTree(json2);
    JsonNode j3 = mapper.readTree(json3);
    ObjectNode jNode = mapper.createObjectNode();
    //add all nodes from j1 to json root, there is only one, but if there will be more it will work.
    j1.fieldNames().forEachRemaining(fieldName -> jNode.replace(fieldName,j1.get(fieldName)));
    //add json array under array field
    jNode.set("array", j2);
    //add all nodes from j3 to json root, if exist for example array or number, they will be replaced!
    j3.forEach(node -> node.fieldNames().forEachRemaining(fieldName -> jNode.replace(fieldName,j1.get(fieldName))));

    System.out.println(mapper.writeValueAsString(jNode))
相关问题