This is a beginner level tutorial on using the Jackson JSON API to
convert between Java objects and JSON data. We have been seeing a
RESTful services tutorial series in the recent past. I will be using
JSON conversion in RESTful services in the coming weeks. This JSON
tutorial is to help started with it.
Java 9 features was announced earlier and it includes a JSON parser that is to be bundled with the java core lib. Once that is available, we may not need a third-party library. Till then, we have to go with an external library.
There are two options we can go with. First one is the popular Jackson JSON processor a third party API. Second one is the JSR 353, Java API for JSON Processing and its reference implementation JSON-P. In this tutorial, we will use the popular option, the Jackson JSON processor.
Java 9 features was announced earlier and it includes a JSON parser that is to be bundled with the java core lib. Once that is available, we may not need a third-party library. Till then, we have to go with an external library.
There are two options we can go with. First one is the popular Jackson JSON processor a third party API. Second one is the JSR 353, Java API for JSON Processing and its reference implementation JSON-P. In this tutorial, we will use the popular option, the Jackson JSON processor.
Jackson JSON Processing
Old jackson API was in codehaus.org and presently it is hosted at github and named as FasterXML/jackson. API’s package structure also changed tocom.fasterxml.jackson.*
. Jackson Processor API library files can be downloaded from http://mvnrepository.com/artifact/com.fasterxml.jackson.coreJava to JSON Conversion
package com.javapapers.java; import java.io.File; import java.io.IOException; import com.fasterxml.jackson.databind.ObjectMapper; public class JavaToJSON { public static void main(String[] args) { Animal crocodile = new Animal(1, "Crocodile", "Wild"); ObjectMapper objectMapper = new ObjectMapper(); try { objectMapper.writeValue(new File("animal.json"), crocodile); } catch (IOException e) { e.printStackTrace(); } try { objectMapper.writerWithDefaultPrettyPrinter().writeValue( new File("prettyanimal.json"), crocodile); } catch (IOException e) { e.printStackTrace(); } } }
JSON to Java Conversion
package com.javapapers.java; import java.io.File; import java.io.IOException; import com.fasterxml.jackson.databind.ObjectMapper; public class JSONToJava { public static void main(String[] args) { Animal animal = null; ObjectMapper objectMapper = new ObjectMapper(); try { animal = objectMapper.readValue(new File("animal.json"), Animal.class); } catch (IOException e) { e.printStackTrace(); } System.out.println(animal); } }
Download Java to JSON to Java Example Project
JSON Conversion Output
animal.json
{"id":1,"firstName":"Crocodile","lastName":"Wild"}
prettyanimal.json
{ "id" : 1, "firstName" : "Crocodile", "lastName" : "Wild" }
SOURCE
No comments:
Post a Comment