Tuesday, 17 March 2020

Jackson: Convert map to JsonNode

'valueToTree' method of ObjectMapper is used to convert a Map to JsonNode.

Example
Map<String, String> map = new HashMap<> ();
map.put("firstName", "Krishna");
map.put("lastName", "Gurram");

ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.valueToTree(map);

App.java
package com.sample.app;

import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class App {

    public static void main(String args[]) {
        Map<String, String> map = new HashMap<> ();
        map.put("firstName", "Krishna");
        map.put("lastName", "Gurram");
        
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.valueToTree(map);

        JsonNode firstNameNode = jsonNode.get("firstName");
        JsonNode lastNameNode = jsonNode.get("lastName");

        System.out.println("First Name : " + firstNameNode.textValue());
        System.out.println("Last Name : " + lastNameNode.textValue());
    }

}

Output
First Name : Krishna
Last Name : Gurram


Previous                                                    Next                                                    Home

No comments:

Post a Comment