JSON also known as JavaScript Object Notation is a widely used format for exchanging data between a server and a client.

In this article, we will see how to parse a JSON input stream using the Jackson library in Java.

Jackson Library:

Jackson is a high-performance JSON parsing and generation library for Java which provides a simple and efficient way to parse JSON data into Java objects.

Let us see how to parse a JSON input using the Jackson library.

Add dependencies

First, let us include the Jackson Library’s dependency in your project. For Maven, please add the following dependency to your pom.xml.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.0</version>
</dependency>

The version I am using above in the dependency XML might not be the latest one. You can visit the Jackson official page and see the latest version.

Import the required classes

import com.fasterxml.jackson.databind.*;
import java.io.*;

Parsing the JSON from the input stream

See the following example on how to parse the JSON from the input stream.

public class JsonParsingExample {
    public static void main(String[] args) {
        try {
            // Create a JSON parser
            ObjectMapper objectMapper = new ObjectMapper();

            // Create an InputStream (you can replace this with your input source)
            InputStream inputStream = new FileInputStream("data.json");

            // Parse the JSON input stream into a JsonNode object
            JsonNode jsonNode = objectMapper.readTree(inputStream);

            // Process the JSON data
            String value = jsonNode.get("key").asText();
            System.out.println("Value of 'key': " + value);

            // Close the input stream
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In the above example, replace "data.json" with the path to your JSON input stream. In this example, we use a JsonNode object to navigate and retrieve data from the JSON structure.

References:

For more information, please visit the Jackson git repository.

https://github.com/FasterXML/jackson

Categorized in:

Tagged in: