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:
xxxxxxxxxx
1
ObjectMapper objectMapper = new ObjectMapper();
2
3
String json = "{\"name\": \"john\"}"; // {"name": "john"}
4
JsonNode node = objectMapper.readTree(json);
5
6
System.out.println(node.get("name").asText()); // john
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:
xxxxxxxxxx
1
import com.fasterxml.jackson.core.JsonProcessingException;
2
import com.fasterxml.jackson.databind.JsonNode;
3
import com.fasterxml.jackson.databind.ObjectMapper;
4
5
public class Program {
6
7
public static void main(String[] args) throws JsonProcessingException {
8
9
ObjectMapper objectMapper = new ObjectMapper();
10
11
String json = "{\"name\": \"john\", \"email\": \"john@mail.com\"}";
12
JsonNode node = objectMapper.readTree(json);
13
14
JsonNode nameNode = node.get("name");
15
JsonNode emailNode = node.get("email");
16
17
System.out.println("name: " + nameNode.asText()); // john
18
System.out.println("email: " + emailNode.asText()); // john@mail.com
19
}
20
}
Output:
xxxxxxxxxx
1
name: john
2
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