2017-04-20 50 views
2
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; 
} 

这项任务年级生记载:如何返回正确的格式JsonString

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

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

回答

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} 
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)) 
相关问题