JSON String to Generic Java Object using JSON-B


In this post, we can see about JSON-BINDING, which is the standard for working between the java object and the json. Json binding has recently been introduced to java as part of the JSR 367 specification. JSON binding api specifies the specifications for converting generic java objects to json format and converting json strings to generic java objects.

It is necessary to convert a json string to generic java object in the spring boot application. Using a json string, a generic java object can be retrieved from a persistence layer like a database. The json string is a text that can be quickly transmitted across the network. In this post, we’ll see how to convert a json string to a generic java bean object.

The javax.json.bind dependency on the spring boot attaches the dependent jars to the spring boot project. Here we see the step-by-step process for building a spring boot application that converts a json string to a generic java object and converts a generic java object to a json string.



Step 1 – Create pom.xml with dependency

The first step is to build a spring boot application. The spring boot framework includes two simple “spring-boot-starter” and “spring-boot-starter-test” dependencies. To add json binding jars to the project, add “javax.json.bind-api” dependency to the pom.xml file. This is a specification api jar that enforces all json binding specifications.

Add the json binding jars to the spring boot program. The default json binding is org.eclipse.yasson. Add “org.eclipse.yasson” and “org.glassfish.javax.json” to the pom.xml file. The pom.xml file below includes all the dependency for json binding.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.5.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.yawintutor</groupId>
	<artifactId>Spring-Application</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringBootJsonbSimple</name>
	<description>Spring Boot Project</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>javax.json.bind</groupId>
			<artifactId>javax.json.bind-api</artifactId>
		</dependency>

		<dependency>
			<groupId>org.eclipse</groupId>
			<artifactId>yasson</artifactId>
			<version>1.0.6</version>
		</dependency>

		<dependency>
			<groupId>org.glassfish</groupId>
			<artifactId>javax.json</artifactId>
			<version>1.1.4</version>
			<scope>provided</scope>
		</dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>


Step 2 – Create Java Bean Class

Build a java bean object that will be transformed to a json object in the spring boot framework. The Java Bean object will contain all private variables and public getter and setter methods. The java bean object must have a default constructor.

The example below shows a sample of the java bean model.

Student.java

package com.yawintutor;

public class Student {

	private int id;

	private String name;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}


Step 3 – JSON Binding API code to convert Generic Java Bean Object

The json binding api supports to create a generic java bean object by taking input as a json string. The example below demonstrates how to build a generic java bean object and how to convert a json string to generic java bean object.

SpringBootJsonbSimpleApplication.java

package com.yawintutor;

import java.util.ArrayList;
import java.util.List;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootJsonbSimpleApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootJsonbSimpleApplication.class, args);

		GenericJavaObjecttoJSON();
		JSONToGenericJavaObject();
	}

	public static void GenericJavaObjecttoJSON() {
		Student student1 = new Student();
		student1.setId(100);
		student1.setName("Yawin");
		
		Student student2 = new Student();
		student2.setId(101);
		student2.setName("Spring Boot");

		List<Student> studentList = new ArrayList<>();
		studentList.add(student1);
		studentList.add(student2);
		
		Jsonb jsonb = JsonbBuilder.create();
		String jsonString = jsonb.toJson(studentList);
		System.out.println("Json format String : " + jsonString);
	}

	@SuppressWarnings("serial")
	public static void JSONToGenericJavaObject() {
		String jsonString = "[{\"id\":100,\"name\":\"Yawin\"},{\"id\":101,\"name\":\"Spring Boot\"}]";

		Jsonb jsonb = JsonbBuilder.create();
		List<Student> studentList = jsonb.fromJson(jsonString, new ArrayList<Student>(){}.getClass().getGenericSuperclass());
		for(Student st : studentList) {
			System.out.println(st.getId() + " " + st.getName());
		}
	}

}

Output


  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.2.5.RELEASE)

2020-03-14 19:14:06.104  INFO 15487 --- [           main] c.y.SpringBootJsonbSimpleApplication     : Starting SpringBootJsonbSimpleApplication on banl1691b9157 with PID 15487 (/Users/knatarajan2/STS/workspace/SpringBootJsonbSimple/target/classes started by knatarajan2 in /Users/knatarajan2/STS/workspace/SpringBootJsonbSimple)
2020-03-14 19:14:06.107  INFO 15487 --- [           main] c.y.SpringBootJsonbSimpleApplication     : No active profile set, falling back to default profiles: default
2020-03-14 19:14:06.516  INFO 15487 --- [           main] c.y.SpringBootJsonbSimpleApplication     : Started SpringBootJsonbSimpleApplication in 0.638 seconds (JVM running for 3.177)
Json format String : [{"id":100,"name":"Yawin"},{"id":101,"name":"Spring Boot"}]
100 Yawin
101 Spring Boot



Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *