EN
Java - parse JSON to Node
6
points
In this short article, we would like to show how to parse JSON to the JsonNode object in Java.
Quick solution:
ObjectMapper objectMapper = new ObjectMapper();
String json = "{\"name\": \"john\"}"; // {"name": "john"}
JsonNode node = objectMapper.readTree(json);
System.out.println(node.get("name").asText()); // john
Practical example
As JsonNode we understand, the object returned from a parser is not related to a specific type. The JsonNode can store any JSON described as nodes tree.
Quick solution:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Program {
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
String json = "{\"name\": \"john\", \"email\": \"john@mail.com\"}";
JsonNode node = objectMapper.readTree(json);
JsonNode nameNode = node.get("name");
JsonNode emailNode = node.get("email");
System.out.println("name: " + nameNode.asText()); // john
System.out.println("email: " + emailNode.asText()); // john@mail.com
}
}
Output:
name: john
email: john@mail.com
Hint: to know how to attach
*.jar
lib to your project read this article.
Link to the library in the Maven repository:
https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind