【发布时间】:2020-07-27 00:19:18
【问题描述】:
请记住,JSON 结构事先是未知的,即它是完全任意的,我们只知道它是 JSON 格式。
例如, 以下 JSON
{
"id": 1,
"name": "Foo",
"price": 123,
"tags": [
{
"Bar":"23",
"Eek":"24"
}
]
}
我们可以这样做来遍历树并跟踪我们想要找出点符号属性名称的深度。
我们如何在编译时获取数据唯一的键,在运行时获取值。
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.ValueNode;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class Main {
public static void main(String[] args) {
File file=new File("src/data.json");
ObjectMapper mapper=new ObjectMapper();
try {
LinkedHashMap<String,String> map= new LinkedHashMap<String, String>();
JsonNode node =mapper.readTree(file);
getKeys("",node, map);
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("Key:"+entry.getKey() + ""+" "+" value:" + entry.getValue());
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void getKeys(String currentpath,JsonNode node,LinkedHashMap map){
if(node.isObject()){
ObjectNode objectNode=(ObjectNode) node;
Iterator<Map.Entry<String, JsonNode>> it=objectNode.fields();
String prefix=currentpath.isEmpty()?"":currentpath+".";
while (it.hasNext()){
SortedMap.Entry<String,JsonNode> iter=it.next();
getKeys(prefix+iter.getKey(),iter.getValue(),map);
}
}else if (node.isArray()){
ArrayNode arrayNode=(ArrayNode) node;
for(int i=0; i<arrayNode.size(); i++){
getKeys(currentpath+i,arrayNode.get(i),map);
}
}
else if(node.isValueNode()) {
ValueNode valueNode=(ValueNode) node;
map.put(currentpath,valueNode.asText());
}
}
}
在运行时只显示用户想要的值。
喜欢
输入:地址.street 输出:“23fn3 伦敦”
【问题讨论】:
-
我没有从那个中得到清楚的东西..