Convert Java String to JSON Object using Jackson


Let us see how to convert a Java String to JSON Object using Jackson Library,

Example - Java String to JSON Object

Java String
String javaJsonString = "{\"name\":\"Chris\",\"age\":22}";


Java Code:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class JavaStringToJson {

    public static void main(String[] args) {
        try {
            String javaJsonString = "{\"name\":\"Chris\",\"age\":22}";
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(javaJsonString);
            String name = jsonNode.get("name").asText();
            int age = jsonNode.get("age").asInt();
            System.out.println(name +" : " + age);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Output:

Chris : 22

-


Have Questions? Post them here!

Top Hashtags:

Advertisements

Advertisements




Advertisements