Object to jsonnode java

Jackson Tree Model

Jackson represents the JSON object model as a tree of JsonNode objects. This is called the Tree Model since it comprises of a tree of JsonNodes, including ObjectNode and ArrayNode. The tree mirrors the structure of the JSON document. It can be created by parsing a JSON document or by creating an in-memory representation.

2. Parsing a JSON File

A JSON file can be parsed and a tree model representation can be created using the ObjectMapper.readTree().

ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree(new File(args[0]));

The resulting tree model can be converted back to a JSON document as follows:

System.out.println(mapper.writeValueAsString(root));

3. Convert a Java Object (POJO) to JsonNode

Let us learn how to build a tree model from a POJO (Plain Old Java Object). Consider these classes:

public class Address < private String address1; private String address2; private String city; private String state; private String zip; >public class User

Instantiate the objects as required:

User user = new User(); user.setFirstName("Harrison"); user.setLastName("Ford"); Address address = new Address(); address.setAddress1("123 Main Street"); address.setCity("Hollywood"); address.setState("CA"); address.setZip("33023"); user.setAddress(address);

A single function call suffices to convert the POJO to a JsonNode.

JsonNode root = mapper.valueToTree(user); System.out.println(mapper.writeValueAsString(root));

4. Convert a JsonNode to POJO

Once you have assembled a tree model from the JsonNode instances, how can you convert it to a POJO? Quite easy and all the contained JsonNode instances are also converted properly.

User user = mapper.treeToValue(root, User.class);

5. Convert Generic Containers to JsonNode

You can build up an object representation from nothing more than Java’s generic containers such as Map and List. Is it possible to convert such a representation to a tree model (JsonNode)? Of course it is. Use ObjectMapper.valueToTree() as before.

Map user = new HashMap<>(); user.put("firstName", "Harrison"); user.put("lastName", "Ford"); user.put("emailAddress", Arrays.asList("harrison@example.com", "hford@actors.com")); Map addr = new HashMap<>(); addr.put("address1", "123 Main Street"); addr.put("address2", null); addr.put("city", "Hollywood"); addr.put("state", "CA"); addr.put("zip", "33023"); user.put("address", addr); JsonNode root = mapper.valueToTree(user); System.out.println(mapper.writeValueAsString(root)); // prints: < "firstName" : "Harrison", "lastName" : "Ford", "emailAddress" : [ "harrison@example.com", "hford@actors.com" ], "address" : < "zip" : "33023", "address2" : null, "city" : "Hollywood", "address1" : "123 Main Street", "state" : "CA" >>

And of course, once you have the JsonNode tree model, you can use Jackson data binding to create a Java object (POJO).

User userAgain = mapper.treeToValue(root, User.class);

6. Iterating over a JsonNode

Once you have a JsonNode, how can you find out what it contains? You can loop over its contents and extract the children.

Find the key names of a JsonNode (assuming it is an ObjectNode). And lookup the value JsonNode using JsonNode.get(String).

JsonNode parent = . ; for (Iterator it = parent.fieldNames() ; it.hasNext() ; ) < String field = it.next(); System.out.println(field + " =>" + parent.get(field)); >

Or iterate over the fields, again assuming it is an ObjectNode:

for (Iterator> it = parent.fields() ; it.hasNext() ; ) < Map.Entrye = it.next(); System.out.println(e.getKey() + " => " + e.getValue()); >

Fetch and iterate over all the elements. This one works with an ArrayNode too.

for (Iterator it = parent.elements() ; it.hasNext() ; )

7. Creating a Tree Model from Scratch

You can also completely generate a tree model from scratch. Start by creating an ObjectNode and populate it using JsonNode.with(). Here we create the above User instance with the associated Address as shown below.

ObjectNode root = mapper.createObjectNode(); root.put("firstName", "Harrison"); root.put("lastName", "Ford"); root.with("address").put("address1", "123 Main Street"); root.with("address").put("address2", null); root.with("address").put("city", "Hollywood"); root.with("address").put("state", "CA"); root.with("address").put("zip", "33023"); System.out.println(mapper.writeValueAsString(root));

8. Adding Items to a List

For adding lists into the JSON tree model, you can start with the method withArray() and add items as shown:

root.withArray(«Genre»).add(«Drama»).add(«Horror»); // results in:

9. Adding from a List

Here is an example of using Java 8 Streams to add nodes from a List:

Arrays.asList(«Stephen King (novel)», «Stanley Kubrick (screenplay)», «Diane Johnson (screenplay)») .stream() .forEach(root.withArray(«Writer»)::add); // looks like:

10. Adding from a Map

And adding to a tree model from a Map is similarly easy:

map.put("cat", "meow"); map.put("dog", "bark"); map.put("cow", "moo"); map .entrySet() .stream() .forEach(e -> root.with("animals").put(e.getKey(), e.getValue())); // output: < "animals" : < "cat" : "meow", "cow" : "moo", "dog" : "bark" >>

11. Using JsonPointer

JsonPointer is a proposed standard for addressing nodes within a JSON document (somewhat similar to XPath for XML documents). Jackson supports extraction of JsonNodes with a JsonPointer expression using the method JsonNode.at().

JsonNode root = mapper.readTree(new File(jsonFile)); String jsonPtr = . ; System.out.println(mapper.writeValueAsString(root.at(jsonPtr)));

Let us see some examples of JsonPointer. Consider this JSON.

Here are some examples of JsonPointer expression evaluation on this document.

/firstName: "Harrison" /emailAddress: [ "harrison@example.com", "hford@actors.com" ] /emailAddress/0: "harrison@example.com" /emailAddress/1: "hford@actors.com" /address: < "zip" : "33023", "address2" : null, "city" : "Hollywood", "address1" : "123 Main Street", "state" : "CA" >/address/zip: "33023"

Summary

This article demonstrated how to easily work with the tree model in JSON. We showed how to parse JSON into JsonNode and also how to extract information from the tree model.

Источник

Convert Java Object to JsonNode using Jackson

In this short article, you’ll learn how to convert a Java Object to a JsonNode Object using the Jackson library.

public class User  public String name; public String email; private String[] roles; private boolean admin; public User()  > public User(String name, String email, String[] roles, boolean admin)  this.name = name; this.email = email; this.roles = roles; this.admin = admin; > // getters and setters, toString() . (omitted for brevity) > 

To convert the above User class instance to a JsonNode object, you can use the valueToTree() method from ObjectMapper , as shown below:

try  // create user object User user = new User("John Doe", "john.doe@example.com", new String[]"Member", "Admin">, true); // create object mapper instance ObjectMapper mapper = new ObjectMapper(); // convert user object to `JsonNode` JsonNode node = mapper.valueToTree(user); // print JSON nodes System.out.println(node.path("name").asText()); System.out.println(node.path("email").asText()); System.out.println(node.path("roles").get(0).asText()); > catch (Exception ex)  ex.printStackTrace(); > 
JsonNode node = mapper.convertValue(user, JsonNode.class); 

The following example demonstrates how to convert a Java Map object to a JsonNode object using the same convertValue() method:

try  // create a map MapString, Object> map = new HashMap>(); map.put("name", "John Deo"); map.put("email", "john.doe@example.com"); map.put("roles", new String[]"Member", "Admin">); map.put("admin", true); // create object mapper instance ObjectMapper mapper = new ObjectMapper(); // convert map to `JsonNode` JsonNode node = mapper.convertValue(map, JsonNode.class); // print JSON nodes System.out.println(node.path("name").asText()); System.out.println(node.path("email").asText()); System.out.println(node.path("roles").get(0).asText()); > catch (Exception ex)  ex.printStackTrace(); > 

To convert an instance of JsonNode to a Java Object, you can use the treeToValue() method from ObjectMapper :

try  // JSON string String json = " + "\"roles\":[\"Member\",\"Admin\"],\"admin\":true>"; // create object mapper instance ObjectMapper mapper = new ObjectMapper(); // convert JSON string to `JsonNode` JsonNode node = mapper.readTree(json); // convert `JsonNode` to `User` object User user = mapper.treeToValue(node, User.class); // print user object System.out.println(user); > catch (Exception ex)  ex.printStackTrace(); > 

Read the guide Working with Tree Model Nodes in Jackson for more JsonNode examples. For more Jackson examples, check out the How to read and write JSON using Jackson in Java tutorial. ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

Working with Tree Model Nodes in Jackson

In this article, you’ll learn how to add, remove, modify, and traverse JSON nodes in Jackson’s tree model. In Jackson, we can use the tree model to represent the JSON data structure and perform different operations. This is especially useful when we cannot map the JSON structure directly to a Java class.

The ObjectMapper class can also be used to construct a hierarchical tree of nodes from JSON data. In the JSON tree model, each node is of type JsonNode and provides different methods to work with specific keys. From the tree model, you can access nodes to read their values.

implementation 'com.fasterxml.jackson.core:jackson-databind:2.10.0' 
dependency> groupId>com.fasterxml.jackson.coregroupId> artifactId>jackson-databindartifactId> version>2.10.0version> dependency> 
// create object mapper ObjectMapper mapper = new ObjectMapper(); // create new node JsonNode node = mapper.createObjectNode(); 

Another way of creating a JsonNode object is parsing a JSON string by using the readValue() method from ObjectMapper , as shown below:

// JSON string String json = ""; // create object mapper instance ObjectMapper mapper = new ObjectMapper(); // convert JSON string to `JsonNode` JsonNode node = mapper.readTree(json); 

Finally, the last way to create a new JsonNode is converting a Java Object by using the valueToTree() method from ObjectMapper :

// create user object User user = new User("John Doe", "john.doe@example.com", new String[]"Member", "Admin">, true); // create object mapper instance ObjectMapper mapper = new ObjectMapper(); // convert user object to `JsonNode` JsonNode node = mapper.valueToTree(user); 

You can simply call the toString() method (or toPrettyString() for pretty print JSON) to get the JSON structure as a string:

String json = node.toString(); // OR String prettyJson = node.toPrettyString(); 
mapper.writeValue(destination, node); 
User user = mapper.treeToValue(node, User.class); 
User user = mapper.convertValue(node, User.class); 
// find top-level node JsonNode contact = node.path("contact"); // find nested node JsonNode city = node.path("address").path("city"); // find and get node value String name = node.path("name").asText(); 
ObjectNode obj = (ObjectNode) node; // add new node obj.put("age", 45); 
ObjectNode obj = (ObjectNode) node; // create address ObjectNode address = mapper.createObjectNode(); address.put("city", "Lahore"); address.put("country", "Pakistan"); // add address node obj.set("address", address); 

To update an existing node, you first need to convert it to ObjectNode . Afterward, you can use the put() method to change the field value, as shown below:

ObjectNode obj = (ObjectNode) node; // change name value obj.put("name", "Tom Lee"); 
ObjectNode obj = (ObjectNode) node; // remove id node obj.remove("id"); 

Since the tree model has a hierarchical structure, we can iterate over all nodes by starting from the root node until we reach the child nodes:

try  // create object mapper instance ObjectMapper mapper = new ObjectMapper(); // convert JSON file to `JsonNode` JsonNode node = mapper.readTree(Paths.get("user.json").toFile()); // print JSON nodes System.out.println("Name: " + node.path("name").asText()); System.out.println("Email: " + node.path("email").asText()); System.out.println("Admin: " + node.path("admin").asBoolean()); // iterate `roles` array System.out.println("Roles: "); for (JsonNode role : node.path("roles"))  System.out.println(role.asText()); > > catch (Exception ex)  ex.printStackTrace(); > 
Name: John Doe Email: john.doe@example.com Admin: true Roles: Member Admin 
[  "name": "John Doe", "email": "john.doe@example.com", "roles": [ "Member", "Admin" ], "admin": true >,  "name": "Tom Lee", "email": "tom.lee@example.com", "roles": [ "Member" ], "admin": false > ] 

Like JSON Object, you can also traverse the above JSON array nodes. All you need to do is just loop over all top-level nodes, as shown below:

try  // create object mapper instance ObjectMapper mapper = new ObjectMapper(); // convert JSON file to `JsonNode` JsonNode nodes = mapper.readTree(Paths.get("users.json").toFile()); // iterate over all users for (JsonNode node : nodes)  // print JSON nodes System.out.println("Name: " + node.path("name").asText()); System.out.println("Email: " + node.path("email").asText()); System.out.println("Admin: " + node.path("admin").asBoolean()); // iterate `roles` System.out.println("Roles: "); for (JsonNode role : node.path("roles"))  System.out.println(role.asText()); > > > catch (Exception ex)  ex.printStackTrace(); > 

For more Jackson examples, check out the How to read and write JSON using Jackson in Java tutorial. ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

Читайте также:  Css selector data value
Оцените статью