Tag Archives: jackson-databind

JAVA : How to convert YAML Documents to JSON List?

Here is code to convert YAML documents to JSON objects by Jackson and snakeyml apis. Jackson also support YAML support.

Pre-Requisite



        <dependencies>
        <!-- Jackson JSON Processor -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.4.1</version>
        </dependency>
        <!-- For YAML -->
        <dependency>
            <groupId>org.yaml</groupId>
            <artifactId>snakeyaml</artifactId>
            <version>1.21</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-yaml</artifactId>
            <version>2.1.2</version>
        </dependency>
    </dependencies>   

Sample YAML Documents File


---
# My personal record
name: Saurabh Kumar Gupta
Title: Sr. Project Lead
skill: JAVA/J2EE
employed: True
domains:
    - Telecom
    - Finance
    - Banking
    - Healthcare
languages:
    ELK: Medium
    JAVA: Expertize
    Scripting: Comfortable
education: |
    MCA
    B.Sc
    Diploma

---
# Gaurav personal record
name: Gaurav Gupta
Title: Project Lead
skill: ELK
employed: True
domains:
    - Telecom
    - Banking
    - Healthcare
languages:
    ELK: Medium
    JAVA: Expertize
    Scripting: Comfortable
    Bigdata: Expertize
education: |
    MCA
    B.Sc

Code to Convert YAML documents to JSON Objects

package com.fiot.examples.yaml;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Iterator;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;

public class ConvertYAMLObjectsToJSON {
	public static void main(String[] args) {
		try (InputStream input = new FileInputStream(new File(
				"F:\\Workspace-Blog\\TestExamples\\src\\main\\resources\\YAMLDocument2.yaml"))) {
			Yaml yaml = new Yaml(new SafeConstructor());
			Iterator iterator = yaml.loadAll(input).iterator();
			while (iterator.hasNext()) {
				System.out.println(iterator.next());
			}
		} catch (Throwable e) {
			System.out.println("ERROR: " + e.getMessage());
		}
	}
}

Output


{name=Saurabh Kumar Gupta, Title=Sr. Project Lead, skill=JAVA/J2EE, employed=true, domains=[Telecom, Finance, Banking, Healthcare], languages={ELK=Medium, JAVA=Expertize, Scripting=Comfortable}, education=MCA
B.Sc
Diploma
}
{name=Gaurav Gupta, Title=Project Lead, skill=ELK, employed=true, domains=[Telecom, Banking, Healthcare], languages={ELK=Medium, JAVA=Expertize, Scripting=Comfortable, Bigdata=Expertize}, education=MCA
B.Sc}

More

To know more about YAML Syntax, Configuration with Java and other supporting language, frameworks and tools, Sample configuration files and JSON and YAML conversion follow below YAML Tutorials and YAML related exceptions follow YAML Issues.

Advertisements

JAVA : How to convert YAML To JSON?

Here is code to convert YAML document to JSON by Jackson and snakeyml apis. Jackson also support YAML support.

Pre-Requisite


<dependencies>
        <!-- Jackson JSON Processor -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.4.1</version>
        </dependency>
        <!-- For YAML -->
        <dependency>
            <groupId>org.yaml</groupId>
            <artifactId>snakeyaml</artifactId>
            <version>1.21</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-yaml</artifactId>
            <version>2.1.2</version>
        </dependency>
    </dependencies>

Sample YAML File


---
# My personal record
name: Saurabh Kumar Gupta
Title: Sr. Project Lead
skill: JAVA/J2EE
employed: True
domains:
    - Telecom
    - Finance
    - Banking
    - Healthcare
languages:
    ELK: Medium
    JAVA: Expertize
    Scripting: Comfortable
education: |
    MCA
    B.Sc
    Diploma
...

Code to convert YAML to JSON data

package com.fiot.examples.yaml;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

public class ConvertYAMLToJSON {
	public static void main(String[] args) {
		String content = "";
		try {
			content = new String(Files.readAllBytes(Paths.get(
					"F:\\Workspace-Blog\\TestExamples\\src\\main\\resources\\YAMLDocument.yaml")));
			System.out.println("*********Content from YAML File ****************");
			System.out.println(content);
			String json = convertYamlToJson(content);
			System.out.println("*********Cnverted JSON from YAML File ****************");
			System.out.println(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static String convertYamlToJson(String yaml) {
		try {
			ObjectMapper yamlReader = new ObjectMapper(new YAMLFactory());
			Object obj = yamlReader.readValue(yaml, Object.class);
			ObjectMapper jsonWriter = new ObjectMapper();
			return jsonWriter.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
		} catch (JsonProcessingException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return null;
	}
}

Output


*********Content from YAML File ****************
---
# My personal record
name: Saurabh Kumar Gupta
Title: Sr. Project Lead
skill: JAVA/J2EE
employed: True
domains:
    - Telecom
    - Finance
    - Banking
    - Healthcare
languages:
    ELK: Medium
    JAVA: Expertize
    Scripting: Comfortable
education: |
    MCA
    B.Sc
    Diploma
...
*********Cnverted JSON from YAML File ****************
{
  "name" : "Saurabh Kumar Gupta",
  "Title" : "Sr. Project Lead",
  "skill" : "JAVA/J2EE",
  "employed" : true,
  "domains" : [ "Telecom", "Finance", "Banking", "Healthcare" ],
  "languages" : {
    "ELK" : "Medium",
    "JAVA" : "Expertize",
    "Scripting" : "Comfortable"
  },
  "education" : "MCA\nB.Sc\nDiploma\n"
}

Below are some online tools to convert YAML/YML to JSON.
https://codebeautify.org/yaml-to-json-xml-csv
http://convertjson.com/yaml-to-json.htm

More

To know more about YAML Syntax, Configuration with Java and other supporting language, frameworks and tools, Sample configuration files and JSON and YAML conversion follow below YAML Tutorials and YAML related exceptions follow YAML Issues.

How to retrieve key Information from JSON Data?

Jackson provide API’s to parse information based on Key  name.  It’s work like DOM parser and make tree of properties in JSON. Based on Path,Jackson retrieve this information for keys.

Pre-Requisite 

Add below jackson-databind-2.8.5.jar in your classpath or make dependency entry in pom.xml file.

  &lt;dependency&gt;
	&lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;
	&lt;artifactId&gt;jackson-databind&lt;/artifactId&gt;
	&lt;version&gt;2.8.5&lt;/version&gt;
  &lt;/dependency&gt;
 

Example

In below example we have some sample JSON Data for Student and by Jackson API will try to retrieve keys information like rollNumber and phoneNumbers.

Sample DATA

{
"rollNumber" : 11,
"firstName" : "Saurabh",
"lastName" : "Gupta",
"permanent" : false,
"address" : {
"addressLine" : "Lake Union Hill Way",
"city" : "Atlanta",
"zipCode" : 50005
},
"phoneNumbers" : [ 2233445566, 3344556677 ],
"cities" : [ "Dallas", "San Antonio", "Irving" ],
"properties" : {
"play" : "Badminton",
"interst" : "Math",
"age" : "34 years"
}
}

Sample Code

package test.facingissesonit.json.jacson;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Iterator;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ReadJsonByKeyName {

	public static void main(String[] args) {
		try
		{
		byte[] jsonData = Files.readAllBytes(Paths.get(&quot;student_data2.txt&quot;));

		ObjectMapper objectMapper = new ObjectMapper();

		//Jacson read JSON like DOM Parser and create tree of properties
		JsonNode rootNode = objectMapper.readTree(jsonData);

		JsonNode idNode = rootNode.path(&quot;rollNumber&quot;);
		System.out.println(&quot;rollNumber = &quot;+idNode.asInt());

		JsonNode phoneNosNode = rootNode.path(&quot;phoneNumbers&quot;);
		Iterator&lt;JsonNode&gt; elements = phoneNosNode.elements();
		while(elements.hasNext()){
			JsonNode phone = elements.next();
			System.out.println(&quot;Phone No = &quot;+phone.asLong());
		}
		}
		catch(JsonProcessingException ex)
		{
			ex.printStackTrace();
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}
	}
}

Output

rollNumber = 11
Phone No = 2233445566
Phone No = 3344556677

More Sample Code

For more java and JDBC codes follow below links

How to create dynamic JSON by Java?

Jackson  provide Java api’s   to create JSON on runtime . These api’s can handle different type of data and objects.

Jacson API’s

Writing Root Object
JsonGenerator.writeStartObject();
JsonGenerator.writeEndObject();

Writing Sub Object
JsonGenerator.writeObjectFieldStart();
JsonGenerator.writeEndObject();

Writing Array
JsonGenerator.writeArrayFieldStart()
JsonGenerator.writeEndObject();

Writing Field Level
JsonGenerator.writeNumberField();
JsonGenerator.writeStringField();
JsonGenerator.writeBooleanField();

Pre-Requisite 

Add below jackson-databind-2.8.5.jar in your classpath or make dependency entry in pom.xml file.

  &lt;dependency&gt;
	&lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;
	&lt;artifactId&gt;jackson-databind&lt;/artifactId&gt;
	&lt;version&gt;2.8.5&lt;/version&gt;
  &lt;/dependency&gt;
 

Example

In below example by Jacson API’s generating JSON on runtime and writing on file.

package test.facingissesonit.json.jacson;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;

public class JsonStreamWriteToFile {

	public static void main(String[] args) {
		Student student = sampleStudentObject();
		try {
			JsonGenerator jsonGenerator = new JsonFactory().createGenerator(new FileOutputStream(&quot;student_data.txt&quot;));
			// for pretty formatted printing
			jsonGenerator.setPrettyPrinter(new DefaultPrettyPrinter());
			// start root from here
			jsonGenerator.writeStartObject();

			jsonGenerator.writeNumberField(&quot;rollNumber&quot;, student.getRollNumber());
			jsonGenerator.writeStringField(&quot;firstName&quot;, student.getFirstName());
			jsonGenerator.writeStringField(&quot;lastName&quot;, student.getLastName());
			jsonGenerator.writeBooleanField(&quot;permanent&quot;, student.isPermanent());

			jsonGenerator.writeObjectFieldStart(&quot;address&quot;); // object writing
			jsonGenerator.writeStringField(&quot;addressLine&quot;, student.getAddress().getAddressLine());
			jsonGenerator.writeStringField(&quot;city&quot;, student.getAddress().getCity());
			jsonGenerator.writeNumberField(&quot;zipCode&quot;, student.getAddress().getZipCode());
			jsonGenerator.writeEndObject(); // address object completed

			jsonGenerator.writeArrayFieldStart(&quot;phoneNumbers&quot;);
			for (long num : student.getPhoneNumbers())
				jsonGenerator.writeNumber(num);
			jsonGenerator.writeEndArray();

			 // start array writing for cities
			jsonGenerator.writeArrayFieldStart(&quot;cities&quot;);
			for (String city : student.getCities())
				jsonGenerator.writeString(city);
			// closing cities array
			jsonGenerator.writeEndArray(); 

			jsonGenerator.writeObjectFieldStart(&quot;properties&quot;);
			Set&lt;String&gt; keySet = student.getProperties().keySet();
			for (String key : keySet) {
				String value = student.getProperties().get(key);
				jsonGenerator.writeStringField(key, value);
			}
			// End of  properties writing
			jsonGenerator.writeEndObject();
			//End root object writing
			jsonGenerator.writeEndObject(); 

			jsonGenerator.flush();
			jsonGenerator.close();

		} catch (IOException ex) {
			ex.printStackTrace();
		}

	}

	public static Student sampleStudentObject() {

		Student student = new Student();
		student.setRollNumber(11);
		student.setFirstName(&quot;Saurabh&quot;);
		student.setLastName(&quot;Gupta&quot;);
		student.setPhoneNumbers(new long[] { 2233445566L, 3344556677L });

		Address add = new Address();
		add.setAddressLine(&quot;Lake Union Hill Way&quot;);
		add.setCity(&quot;Atlanta&quot;);
		add.setState(&quot;GA&quot;);
		add.setZipCode(50005);
		student.setAddress(add);

		List&lt;String&gt; cities = new ArrayList&lt;String&gt;();
		cities.add(&quot;Dallas&quot;);
		cities.add(&quot;San Antonio&quot;);
		cities.add(&quot;Irving&quot;);
		student.setCities(cities);

		Map&lt;String, String&gt; props = new HashMap&lt;String, String&gt;();
		props.put(&quot;age&quot;, &quot;34 years&quot;);
		props.put(&quot;interst&quot;, &quot;Math&quot;);
		props.put(&quot;play&quot;, &quot;Badminton&quot;);

		student.setProperties(props);

		return student;
	}
}

Model Object

Student and Address classes are required to execute these code

package test.facingissesonit.json.jacson;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class Student {
	private int rollNumber;
	private String firstName;
	private String lastName;
	private boolean permanent;
	private Address address;
	private long[] phoneNumbers;
	private List&lt;String&gt; cities;
	private Map&lt;String, String&gt; properties;
	@Override
	public String toString()
	{
		StringBuffer sb=new StringBuffer();
		sb.append(&quot;==============Student Information================\n&quot;);
		sb.append(&quot;rollNumber=&quot;).append(rollNumber).append(&quot;\n&quot;);
		sb.append(&quot;firstName=&quot;).append(firstName).append(&quot;\n&quot;);
		sb.append(&quot;lastName=&quot;).append(lastName).append(&quot;\n&quot;);
		sb.append(&quot;permanent=&quot;).append(permanent).append(&quot;\n&quot;);
		sb.append(&quot;adress=&quot;).append(address).append(&quot;\n&quot;);
		sb.append(&quot;phoneNumbers=&quot;).append(Arrays.toString(phoneNumbers)).append(&quot;\n&quot;);
		sb.append(&quot;cities=&quot;).append(Arrays.toString(cities.toArray(new String[cities.size()]))).append(&quot;\n&quot;);
		sb.append(&quot;properties=&quot;).append(properties).append(&quot;\n&quot;);
		return sb.toString();
	}
	public int getRollNumber() {
		return rollNumber;
	}
	public void setRollNumber(int rollNumber) {
		this.rollNumber = rollNumber;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public boolean isPermanent() {
		return permanent;
	}
	public void setPermanent(boolean permanent) {
		this.permanent = permanent;
	}
	public Address getAddress() {
		return address;
	}
	public void setAddress(Address address) {
		this.address = address;
	}
	public long[] getPhoneNumbers() {
		return phoneNumbers;
	}
	public void setPhoneNumbers(long[] phoneNumbers) {
		this.phoneNumbers = phoneNumbers;
	}
	public List&lt;String&gt; getCities() {
		return cities;
	}
	public void setCities(List&lt;String&gt; cities) {
		this.cities = cities;
	}
	public Map&lt;String, String&gt; getProperties() {
		return properties;
	}
	public void setProperties(Map&lt;String, String&gt; properties) {
		this.properties = properties;
	}

}

package test.facingissesonit.json.jacson;

public class Address {
private String addressLine;
private String city;
private String state;
private int zipCode;
@Override
public String toString()
{
	StringBuffer sb=new StringBuffer();
	sb.append(&quot;AddressLine=&quot;).append(addressLine).append(&quot;\n&quot;);
	sb.append(&quot;city=&quot;).append(city).append(&quot;\n&quot;);
	sb.append(&quot;state=&quot;).append(state).append(&quot;\n&quot;);
	sb.append(&quot;zipCode=&quot;).append(zipCode).append(&quot;\n&quot;);
	return sb.toString();
}
public String getAddressLine() {
	return addressLine;
}
public void setAddressLine(String addressLine) {
	this.addressLine = addressLine;
}
public String getCity() {
	return city;
}
public void setCity(String city) {
	this.city = city;
}
public String getState() {
	return state;
}
public void setState(String state) {
	this.state = state;
}
public int getZipCode() {
	return zipCode;
}
public void setZipCode(int zipCode) {
	this.zipCode = zipCode;
}
}

Output

Generated output on Student_data.txt file

{
  &quot;rollNumber&quot; : 11,
  &quot;firstName&quot; : &quot;Saurabh&quot;,
  &quot;lastName&quot; : &quot;Gupta&quot;,
  &quot;permanent&quot; : false,
  &quot;address&quot; : {
    &quot;addressLine&quot; : &quot;Lake Union Hill Way&quot;,
    &quot;city&quot; : &quot;Atlanta&quot;,
    &quot;zipCode&quot; : 50005
  },
  &quot;phoneNumbers&quot; : [ 2233445566, 3344556677 ],
  &quot;cities&quot; : [ &quot;Dallas&quot;, &quot;San Antonio&quot;, &quot;Irving&quot; ],
  &quot;properties&quot; : {
    &quot;play&quot; : &quot;Badminton&quot;,
    &quot;interst&quot; : &quot;Math&quot;,
    &quot;age&quot; : &quot;34 years&quot;
  }
}

More Sample Code

For more java and JDBC codes follow below links

How to Convert JSON data from file to ArrayList?

Jackson provide api’s  to convert JSON data to Collections Objects like Map, ArrayList etc.

In below example file student_data.txt having collections of students data in JSON form and through these Jacson API’s will convert JSON data to ArrayList java object.

Pre-Requisite 

Add below jackson-databind-2.8.5.jar in your classpath or make dependency entry in pom.xml file.

  &lt;dependency&gt;
	&lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;
	&lt;artifactId&gt;jackson-databind&lt;/artifactId&gt;
	&lt;version&gt;2.8.5&lt;/version&gt;
  &lt;/dependency&gt;
 

Sample Data

 Add below content in  student_data.txt

[
{
  &quot;rollNumber&quot; : 11,
  &quot;firstName&quot; : &quot;Saurabh&quot;,
  &quot;lastName&quot; : &quot;Gupta&quot;,
  &quot;permanent&quot; : false,
  &quot;address&quot; : {
    &quot;addressLine&quot; : &quot;Lake Union Hill Way&quot;,
    &quot;city&quot; : &quot;Atlanta&quot;,
    &quot;zipCode&quot; : 50005
  },
  &quot;phoneNumbers&quot; : [ 2233445566, 3344556677 ],
  &quot;cities&quot; : [ &quot;Dallas&quot;, &quot;San Antonio&quot;, &quot;Irving&quot; ],
  &quot;properties&quot; : {
    &quot;play&quot; : &quot;Badminton&quot;,
    &quot;interst&quot; : &quot;Math&quot;,
    &quot;age&quot; : &quot;34 years&quot;
  }
},
{
  &quot;rollNumber&quot; : 11,
  &quot;firstName&quot; : &quot;Gaurav&quot;,
  &quot;lastName&quot; : &quot;Khaira&quot;,
  &quot;permanent&quot; : true,
  &quot;address&quot; : {
    &quot;addressLine&quot; : &quot; 5770 Shiloh woods dr&quot;,
    &quot;city&quot; : &quot;Cumming&quot;,
    &quot;zipCode&quot; : 50007
  },
  &quot;phoneNumbers&quot; : [ 2233445567, 3344556678 ],
  &quot;cities&quot; : [ &quot;New York&quot;, &quot;Austin&quot;, &quot;Plano&quot; ],
  &quot;properties&quot; : {
    &quot;play&quot; : &quot;Baseball&quot;,
    &quot;interst&quot; : &quot;Science&quot;,
    &quot;age&quot; : &quot;36 years&quot;
  }
}
]

 

Example 

package test.facingissesonit.json.jacson;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ConvertJsonToArrayList {

	public static void main(String[] args) {
		try
		{
		byte[] mapData = Files.readAllBytes(Paths.get(&quot;student_data.txt&quot;));
		Student[] studentArr = null;

		ObjectMapper objectMapper = new ObjectMapper();
		studentArr = objectMapper.readValue(mapData, Student[].class);
		List&lt;Student&gt; studentList=Arrays.asList(studentArr);
		System.out.println(&quot;Student 1 \n&quot;+studentList.get(0));
		System.out.println(&quot;Student 2 \n&quot;+studentList.get(1));

		}
		catch(JsonMappingException ex)
		{
			ex.printStackTrace();
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}
	}
}

 

Model Classes

Below Student and Address are required classes for execute this code.

package test.facingissesonit.json.jacson;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class Student {
	private int rollNumber;
	private String firstName;
	private String lastName;
	private boolean permanent;
	private Address address;
	private long[] phoneNumbers;
	private List&lt;String&gt; cities;
	private Map&lt;String, String&gt; properties;
	@Override
	public String toString()
	{
		StringBuffer sb=new StringBuffer();
		sb.append(&quot;==============Student Information================\n&quot;);
		sb.append(&quot;rollNumber=&quot;).append(rollNumber).append(&quot;\n&quot;);
		sb.append(&quot;firstName=&quot;).append(firstName).append(&quot;\n&quot;);
		sb.append(&quot;lastName=&quot;).append(lastName).append(&quot;\n&quot;);
		sb.append(&quot;permanent=&quot;).append(permanent).append(&quot;\n&quot;);
		sb.append(&quot;adress=&quot;).append(address).append(&quot;\n&quot;);
		sb.append(&quot;phoneNumbers=&quot;).append(Arrays.toString(phoneNumbers)).append(&quot;\n&quot;);
		sb.append(&quot;cities=&quot;).append(Arrays.toString(cities.toArray(new String[cities.size()]))).append(&quot;\n&quot;);
		sb.append(&quot;properties=&quot;).append(properties).append(&quot;\n&quot;);
		return sb.toString();
	}
	public int getRollNumber() {
		return rollNumber;
	}
	public void setRollNumber(int rollNumber) {
		this.rollNumber = rollNumber;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public boolean isPermanent() {
		return permanent;
	}
	public void setPermanent(boolean permanent) {
		this.permanent = permanent;
	}
	public Address getAddress() {
		return address;
	}
	public void setAddress(Address address) {
		this.address = address;
	}
	public long[] getPhoneNumbers() {
		return phoneNumbers;
	}
	public void setPhoneNumbers(long[] phoneNumbers) {
		this.phoneNumbers = phoneNumbers;
	}
	public List&lt;String&gt; getCities() {
		return cities;
	}
	public void setCities(List&lt;String&gt; cities) {
		this.cities = cities;
	}
	public Map&lt;String, String&gt; getProperties() {
		return properties;
	}
	public void setProperties(Map&lt;String, String&gt; properties) {
		this.properties = properties;
	}

}

package test.facingissesonit.json.jacson;

public class Address {
private String addressLine;
private String city;
private String state;
private int zipCode;
@Override
public String toString()
{
	StringBuffer sb=new StringBuffer();
	sb.append(&quot;AddressLine=&quot;).append(addressLine).append(&quot;\n&quot;);
	sb.append(&quot;city=&quot;).append(city).append(&quot;\n&quot;);
	sb.append(&quot;state=&quot;).append(state).append(&quot;\n&quot;);
	sb.append(&quot;zipCode=&quot;).append(zipCode).append(&quot;\n&quot;);
	return sb.toString();
}
public String getAddressLine() {
	return addressLine;
}
public void setAddressLine(String addressLine) {
	this.addressLine = addressLine;
}
public String getCity() {
	return city;
}
public void setCity(String city) {
	this.city = city;
}
public String getState() {
	return state;
}
public void setState(String state) {
	this.state = state;
}
public int getZipCode() {
	return zipCode;
}
public void setZipCode(int zipCode) {
	this.zipCode = zipCode;
}
}

Output

Below is console output generated by program which is from Java Object.

Student 1
==============Student Information================
rollNumber=11
firstName=Saurabh
lastName=Gupta
permanent=false
adress=AddressLine=Lake Union Hill Way
city=Atlanta
state=null
zipCode=50005

phoneNumbers=[2233445566, 3344556677]
cities=[Dallas, San Antonio, Irving]
properties={play=Badminton, interst=Math, age=34 years}

Student 2
==============Student Information================
rollNumber=11
firstName=Gaurav
lastName=Khaira
permanent=true
adress=AddressLine= 5770 Shiloh woods dr
city=Cumming
state=null
zipCode=50007

phoneNumbers=[2233445567, 3344556678]
cities=[New York, Austin, Plano]
properties={play=Baseball, interst=Science, age=36 years}

More Sample Code

For more java and JDBC codes follow below links

How to Convert JSON to Java Object and Java Object to JSON?

In below java codes consider both the cases from JSON to Java Object and Java Object to JSON by ObjectMapper by Jacson API’s

I have given generic method for both the cases as convertJavaObjectToJSON and convertJSONToJavaObject.

Pre-Requisite : Add below jackson-databind-2.8.5.jar in your classpath or make dependency entry in pom.xml file.

  &lt;dependency&gt;
	&lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;
	&lt;artifactId&gt;jackson-databind&lt;/artifactId&gt;
	&lt;version&gt;2.8.5&lt;/version&gt;
  &lt;/dependency&gt;
 

JAVA and JSON Conversion Example:

Below is complete example for conversion of both the cases.

ObjectMapper.readValue() :Convert JSON String to Java Object

ObjectMapper.writeValue() : Convert JAVA Object to JSON

package test.facingissesonit.json.jacson;

import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class JsonAndJavaObjectConversion {

	public static void main(String[] args) {
		System.out.println(&quot;=================Convert Student Java Object to JSON==============&quot;);
		// convert Object to json string
		Student student = sampleStudentObject();

		String studentStr = convertJavaObjectToJSON(student);
		System.out.println(&quot;Student JSON Data \n&quot; + studentStr);
		System.out.println(&quot;=================Convert JSON DATA  to Student JAVA Object==============&quot;);
		Object object = convertJSONToJavaObject(studentStr, Student.class);
		if (object != null &amp;&amp; object instanceof Student) {
			System.out.println(&quot;Student Object\n&quot; + (Student) object);
		}

	}
	//Generic Method to convert JSON object to Java Object
	public static Object convertJSONToJavaObject(String strJsonData, Class className) {
		try {
			// ObjectMapper new instance
			ObjectMapper objectMapper = new ObjectMapper();
			// //convert json data from file text to object
			return objectMapper.readValue(strJsonData, className);
		} catch (JsonMappingException ex) {
			ex.printStackTrace();
		} catch (JsonGenerationException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return null;
	}
    //Generic Method to convert Java object to JSON
	public static String convertJavaObjectToJSON(Object javaObject) {
		StringWriter jsonStr = null;
		try {

			// ObjectMapper new instance
			ObjectMapper objectMapper = new ObjectMapper();
			// configure Object mapper for pretty print
			objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);

			// writing to console, can write to any output stream such as file
			jsonStr = new StringWriter();
			objectMapper.writeValue(jsonStr, javaObject);

		} catch (JsonMappingException ex) {
			ex.printStackTrace();
		} catch (JsonGenerationException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return jsonStr.toString();
	}

	public static Student sampleStudentObject() {

		Student student = new Student();
		student.setRollNumber(11);
		student.setFirstName(&quot;Saurabh&quot;);
		student.setLastName(&quot;Gupta&quot;);
		student.setPhoneNumbers(new long[] { 2233445566L, 3344556677L });

		Address add = new Address();
		add.setAddressLine(&quot;Lake Union Hill Way&quot;);
		add.setCity(&quot;Atlanta&quot;);
		add.setState(&quot;GA&quot;);
		add.setZipCode(50005);
		student.setAddress(add);

		List&lt;String&gt; cities = new ArrayList&lt;String&gt;();
		cities.add(&quot;Dallas&quot;);
		cities.add(&quot;San Antonio&quot;);
		cities.add(&quot;Irving&quot;);
		student.setCities(cities);

		Map&lt;String, String&gt; props = new HashMap&lt;String, String&gt;();
		props.put(&quot;age&quot;, &quot;34 years&quot;);
		props.put(&quot;interst&quot;, &quot;Math&quot;);
		props.put(&quot;play&quot;, &quot;Badminton&quot;);

		student.setProperties(props);

		return student;
	}

}

Model Classes :

package test.facingissesonit.json.jacson;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class Student {
	private int rollNumber;
	private String firstName;
	private String lastName;
	private boolean permanent;
	private Address address;
	private long[] phoneNumbers;
	private List&lt;String&gt; cities;
	private Map&lt;String, String&gt; properties;
	@Override
	public String toString()
	{
		StringBuffer sb=new StringBuffer();
		sb.append(&quot;==============Student Information================\n&quot;);
		sb.append(&quot;rollNumber=&quot;).append(rollNumber).append(&quot;\n&quot;);
		sb.append(&quot;firstName=&quot;).append(firstName).append(&quot;\n&quot;);
		sb.append(&quot;lastName=&quot;).append(lastName).append(&quot;\n&quot;);
		sb.append(&quot;permanent=&quot;).append(permanent).append(&quot;\n&quot;);
		sb.append(&quot;adress=&quot;).append(address).append(&quot;\n&quot;);
		sb.append(&quot;phoneNumbers=&quot;).append(Arrays.toString(phoneNumbers)).append(&quot;\n&quot;);
		sb.append(&quot;cities=&quot;).append(Arrays.toString(cities.toArray(new String[cities.size()]))).append(&quot;\n&quot;);
		sb.append(&quot;properties=&quot;).append(properties).append(&quot;\n&quot;);
		return sb.toString();
	}
	public int getRollNumber() {
		return rollNumber;
	}
	public void setRollNumber(int rollNumber) {
		this.rollNumber = rollNumber;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public boolean isPermanent() {
		return permanent;
	}
	public void setPermanent(boolean permanent) {
		this.permanent = permanent;
	}
	public Address getAddress() {
		return address;
	}
	public void setAddress(Address address) {
		this.address = address;
	}
	public long[] getPhoneNumbers() {
		return phoneNumbers;
	}
	public void setPhoneNumbers(long[] phoneNumbers) {
		this.phoneNumbers = phoneNumbers;
	}
	public List&lt;String&gt; getCities() {
		return cities;
	}
	public void setCities(List&lt;String&gt; cities) {
		this.cities = cities;
	}
	public Map&lt;String, String&gt; getProperties() {
		return properties;
	}
	public void setProperties(Map&lt;String, String&gt; properties) {
		this.properties = properties;
	}

}

package test.facingissesonit.json.jacson;

public class Address {
private String addressLine;
private String city;
private String state;
private int zipCode;
@Override
public String toString()
{
	StringBuffer sb=new StringBuffer();
	sb.append(&quot;AddressLine=&quot;).append(addressLine).append(&quot;\n&quot;);
	sb.append(&quot;city=&quot;).append(city).append(&quot;\n&quot;);
	sb.append(&quot;state=&quot;).append(state).append(&quot;\n&quot;);
	sb.append(&quot;zipCode=&quot;).append(zipCode).append(&quot;\n&quot;);
	return sb.toString();
}
public String getAddressLine() {
	return addressLine;
}
public void setAddressLine(String addressLine) {
	this.addressLine = addressLine;
}
public String getCity() {
	return city;
}
public void setCity(String city) {
	this.city = city;
}
public String getState() {
	return state;
}
public void setState(String state) {
	this.state = state;
}
public int getZipCode() {
	return zipCode;
}
public void setZipCode(int zipCode) {
	this.zipCode = zipCode;
}
}

Output:

=================Convert Student Java Object to JSON==============
Student JSON Data
{
  &quot;rollNumber&quot; : 11,
  &quot;firstName&quot; : &quot;Saurabh&quot;,
  &quot;lastName&quot; : &quot;Gupta&quot;,
  &quot;permanent&quot; : false,
  &quot;address&quot; : {
    &quot;addressLine&quot; : &quot;Lake Union Hill Way&quot;,
    &quot;city&quot; : &quot;Atlanta&quot;,
    &quot;state&quot; : &quot;GA&quot;,
    &quot;zipCode&quot; : 50005
  },
  &quot;phoneNumbers&quot; : [ 2233445566, 3344556677 ],
  &quot;cities&quot; : [ &quot;Dallas&quot;, &quot;San Antonio&quot;, &quot;Irving&quot; ],
  &quot;properties&quot; : {
    &quot;play&quot; : &quot;Badminton&quot;,
    &quot;interst&quot; : &quot;Math&quot;,
    &quot;age&quot; : &quot;34 years&quot;
  }
}
=================Convert JSON DATA  to Student JAVA Object==============
Student Object
==============Student Information================
rollNumber=11
firstName=Saurabh
lastName=Gupta
permanent=false
adress=AddressLine=Lake Union Hill Way
city=Atlanta
state=GA
zipCode=50005

phoneNumbers=[2233445566, 3344556677]
cities=[Dallas, San Antonio, Irving]
properties={play=Badminton, interst=Math, age=34 years}

More Sample Code

For more java and JDBC codes follow below links