JavaScript Object Notation JSON is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications.
One of the common task in Java web application, particularly the ones which deals with web services are parsing JSON messages. Many times you need to parse JSON to create a Java object like parsing a JSON message to create a POJO, for example, an Order or a Book. Representing JSON in Java is easy, it's like a String value but unfortunately, JDK doesn't provide any standard API to parse JSON in Java. . There are many good open-source JSON parsing libraries you can use to parse any kind of JSON in your Java program.
1. Parsing JSON using Jackson in Java
It's pretty easy to parse JSON messages into a Java object using Jackson. You just need to use the ObjectMapper class, which provides the readValue() method. This method can convert JSON String to Java object, that's why it takes JSON as a parameter and the Class instance in which you want to parse your JSON.
Here is an example to convert our JSON String to an EBook object in Java:
ObjectMapper mapper = new ObjectMapper();
EBook effectiveJava = mapper.readValue(JSON, EBook.class);
Also, the readValue method throws IOException. I have omitted the try-catch statement for the sake of readability but you need to either throw that exception or catch it using the try-catch-finally block.
This is probably the single most important JSON library you should know as a Java developer. It's feature-rich and also quite fast. Usually, you don't need any other JSON library if you are using Jackson.
Btw, to use the Jackson library, you need to use either jackson-core.jar, jackson-databind.jar, or jackson-annotations.jar in your classpath. Alternatively, you can also add the following Maven dependency in your Eclipse project's pom.xml, if you are using Maven in Eclipse:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.2.3</version>
</dependency>
ObjectMapper mapper = new ObjectMapper();
try
{
EBook effectiveJava = mapper.readValue(JSON, EBook.class);
System.out.println("Java object after parsing JSON using Jackson"); System.out.println(effectiveJava);
}
catch (IOException e)
{
e.printStackTrace();
}
No comments:
Post a Comment