已知目标json的所有key-value,以及key所属路径,生成json
例如:
"a.b.c":"v1"
"a.b.d":"v2"
"a.e":"v3"
生成json:
{
"a":{
"b":{
"d":"v2",
"c":"v1"
},
"e":"v3"
}
}
代码如下:
package common.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.util.HashMap;
import java.util.Map;
public class GenerateJsonUtils {
public static void main(String[] args) throws JsonProcessingException {
Map<String, String> data = new HashMap<>();
data.put("a.b.c", "v1");
data.put("a.b.d", "v2");
data.put("a.e", "v3");
System.out.println(generateJson(data));
}
public static String generateJson(Map<String, String> data) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
ObjectNode rootNode = mapper.createObjectNode();
for (Map.Entry<String, String> item : data.entrySet()) {
buildJsonByPath(item.getKey(), item.getValue(), rootNode, mapper);
}
return mapper.writeValueAsString(rootNode);
}
private static void buildJsonByPath(String path, String value, ObjectNode rootNode, ObjectMapper mapper) {
String[] arr = path.split("\\.");
JsonNode ref = rootNode;
JsonNode next;
for (int i = 0; i < arr.length; i++) {
next = ref.get(arr[i]);
if (next == null) {
if (i == arr.length - 1) {
((ObjectNode) ref).put(arr[i], value);
} else {
String[] copy = new String[arr.length - i - 1];
System.arraycopy(arr, i + 1, copy, 0, copy.length);
ObjectNode node = createObjectNode(copy, value, mapper);
((ObjectNode) ref).set(arr[i], node);
}
break;
}
ref = next;
}
}
private static ObjectNode createObjectNode(String[] arr, String value, ObjectMapper mapper) {
if (arr.length == 1) {
ObjectNode node = mapper.createObjectNode();
node.put(arr[0], value);
return node;
}
String[] copy = new String[arr.length - 1];
System.arraycopy(arr, 1, copy, 0, copy.length);
ObjectNode node = mapper.createObjectNode();
node.set(arr[0], createObjectNode(copy, value, mapper));
return node;
}
}