在java中,我试图将嵌套的JSON转换为平面JSON。下面是输入负载。
输入有效负载:
{
"root": {
"data": {
"a": "1",
"b": {
"c": "2"
},
"test": [
{
"e": "3"
},
{
"f": "4"
}
],
"test1": [
{
"g": "5"
}
],
"test2": [
1,
2,
3
]
}
}
}
我尝试将上面的有效负载转换为以下扁平 JSON。
{
"root.data.a":"1",
"root.data.b.c":"2",
"root.data.test[]":[
{
"e": "3"
},
{
"f": "4"
}
],
"root.data.test1[].g":"5",
"root.data.test2":[1,2,3]
}
在上面的 JSON 中,转换为平面 JSON 时使用以下条件。
如果 JSONObject 由嵌套 JSONObject 和除 JSONArray 之外的任何数据类型的值组成,则平面 JSON 的键和值必须为
"root.data.a"
且值为 1。如果 JSONObject 由 JSONArray 组成,并且 JSONArray 的长度大于 1,则扁平 JSON 的键必须为
“root.data.test[]”
,值必须为完整 JSONArray。如果 JSONObject 由 JSONArray 组成,并且 JSONArray 的长度为 1,则扁平 JSON 必须键必须由 JSON 数组中的所有 JSON 对象元素组成,
"root.data.test1[].g"
值为“5”。如果 JSON 键的值为没有任何 JSON 对象的数组,则将值分配给平面 JSON 中的该路径,如键为
"root.data.test2"
和值为[1,2,3]
那么,如何将输入 JSON 转换为平面 JSON 。
最佳答案
public class Sample {
public static void main(String[] args) {
Sample a= new Sample();
a.testCreatingKeyValues();
}
String json =
"{\n \"root\": {\n \"data\": {\n \"a\": \"1\",\n \"b\": {\n \"c\": \"2\"\n },\n \"test\": [\n {\n \"e\": \"3\"\n },\n {\n \"f\": \"4\"\n }\n ],\n \"test1\": [\n {\n \"g\": \"5\"\n }\n ],\n \"test2\": [\n 1,\n 2,\n 3\n ]\n }\n }\n}";
// @Test
public void testCreatingKeyValues() {
Map<String, Object> map = new HashMap<String, Object>();
try {
addKeys("", new ObjectMapper().readTree(json), map);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(map);
}
private void addKeys(String currentPath, JsonNode jsonNode, Map<String, Object> map) {
if (jsonNode.isObject()) {
ObjectNode objectNode = (ObjectNode) jsonNode;
Iterator<Map.Entry<String, JsonNode>> iter = objectNode.fields();
String pathPrefix = currentPath.isEmpty() ? "" : currentPath + ".";
while (iter.hasNext()) {
Map.Entry<String, JsonNode> entry = iter.next();
addKeys(pathPrefix + entry.getKey(), entry.getValue(), map);
}
} else if (jsonNode.isArray()) {
ArrayNode arrayNode = (ArrayNode) jsonNode;
map.put(currentPath+"[]", arrayNode);
} else if (jsonNode.isValueNode()) {
ValueNode valueNode = (ValueNode) jsonNode;
map.put(currentPath, valueNode.asText());
}
}
}
给出输出:
{root.data.b.c=2, root.data.test2[]=[1,2,3], root.data.test1[]=[{"g":"5"}], root.data.a=1, root.data.test[]=[{"e":"3"},{"f":"4"}]}
关于JAVA JSON从嵌套JSON到平面JSON的动态转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61007688/