Have in mind that the JSON structure is not known before hand i.e. it is completely arbitrary, we only know that it is JSON format.
For example, The following JSON
{
"id": 1,
"name": "Foo",
"price": 123,
"tags": [
{
"Bar":"23",
"Eek":"24"
}
]
}
We can do this to traverse the tree and keep track of how deep we want to figure out dot notation property names.
How can we get the data only keys at compile time and values at run time.
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());
}
}
}
At Run time Only display the values what user wants.
like
input:Address.street output:"23fn3 london"