Do JSON in One line with Jackson + Java
Goal: To list some one line code from jackson
1 min readSep 26, 2016
Get field by FieldPath
JsonNode result =jsonobject.at("/students/subjects/english/result");
Convert List to ArrayNode
ArrayNode arrayNode = new ObjectMapper().convertValue(docs, ArrayNode.class);
Find all values in a list for a key in all nested Json object
/* If the json document (json) is as following [{
"id": "NL",
"document": {
"Country": {
"label": "Netherlands",
"code": "NL",
"translations": [{
"languagecode": "en",
"label": "Netherlands"
},
{
"languagecode": "de",
"label": "Niederlande"
},
{
"languagecode": "es",
"label": "PaÃses Bajos"
},
{
"languagecode": "fr",
"label": "Pays-Bas"
},
{
"languagecode": "ja",
"label": "オランダ"
},
{
"languagecode": "it",
"label": "Paesi Bassi"
}]
}
}
},
{
"id": "AN",
"document": {
"Country": {
"label": "Netherlands Antilles",
"code": "AN",
"translations": []
}
}
},
{
"id": "NET",
"document": {
"Skill": {
"referenceId": "02",
"label": ".NET",
"code": "02",
"category": "Software Development"
}
}
}];*/
List<JsonNode> labels = json.findValues("labels");/*** The output labels will be as foolowing ***/["Netherlands", "Netherlands", "Niederlande", "PaÃses Bajos", "Pays-Bas", "オランダ", "Paesi Bassi", "Netherlands Antilles", ".NET"]
Iterate by Key
Iterator<Entry<String, JsonNode>> p = jsonNode.fields();
Convert JsonNode to key-value Map
CollectionType mapCollectionType = new ObjectMapper().getTypeFactory().constructCollectionType(List.class, Map.class);try {
List<Map<String, String>> map = new ObjectMapper().readValue(jsonnode.toString(), mapCollectionType);} catch (Exception e) {
e.printStackTrace();
}
Find Parent Node
JsonNode parent = jsonNode.findParent("fieldsName");
Read from Stream
JsonNode node= new ObjectMapper().readTree(inputstream);
Write to File
File file = new File("nodes.json");
PrintWriter fileWriter = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));
ObjectMapper mapper = new ObjectMapper();fileWriter.write(mapper.writeValueAsString(node));
fileWriter.close();