Category Archives: JSON

JSON Properties Order Change (Jackson)


@JsonPropertyOrder annotation use to define the order of JSON properties while serialization from Java to JSON. This annotation always use on class level.

@JsonPropertyOrder on Class Level

@JsonPropertyOrder({"firstName","lastName","rollNumber"})
public class StudentDetail
{	
		@JsonProperty(value = "id")
		private int rollNumber;
		
		@JsonProperty(value = "firstName")
		private String first_name;
		
		@JsonProperty(value = "lastName")
		private String last_name;
}

Here you will see complete example of JSON properties name change and define order of  JSON  propertis.

Complete Example

@JsonPropertyOrder({"firstName","lastName","rollNumber"})
public class StudentDetail
{	
		@JsonProperty(value = "id")
		private int rollNumber;
		
		@JsonProperty(value = "firstName")
		private String first_name;
		
		@JsonProperty(value = "middleName")
		private String middle_name;
		
		@JsonProperty(value = "lastName", index=1)
		private String last_name;

		public StudentDetail()
		{
			
		}
		//Getter and Setter

                //toString() method
}

Code to convert  Java object to JSON.

public class JsonPropertiesOrder {
	public static void main(String [] args)
	{
	StudentDetail student=new StudentDetail();
	student.setFirst_name("Saurabh");
	student.setRollNumber(25);
	student.setLast_name("Gupta");
	System.out.println(student);
	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
		String json =objectMapper.writeValueAsString(student);
		System.out.println(json);

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

Output


StudentDetail [rollNumber=25, firstName=Saurabh, lastName=Gupta]
{
"firstName" : "Saurabh",
"lastName" : "Gupta",
"id" : 25
}

References

https://github.com/FasterXML/jackson-annotations

You would like to see

Follow below link to learn more on JSON and  JSON issues solutions:

Advertisements

JSON Properties Name and Index Change (Jackson)


@JsonProperty annotation use to rename of properties for JSON while serializing and deserializing to/from Java Class. This annotation can apply on properties and getter/setter method level.

@JsonProperty on Properties Level

public class StudentDetail
{	
		@JsonProperty(value = "id")
		private int rollNumber;
		
		@JsonProperty(value = "firstName")
		private String first_name;
		
		@JsonProperty(value = "lastName")
		private String last_name;
}

@JsonProperty on getter/setter Level

  • @JsonProperty at getter level change name, when serializing Java to JSON.
  • @JsonProperty at setter level change name, when de-serializing Java to JSON.

public class StudentDetail
{			
		private int rollNumber;	
		private String first_name;
		private String last_name;

          @JsonProperty(value = "id")
          public int getRollNumber() {
		        return rollNumber;
          }
           public void setRollNumber(int rollNumber) {
			this.rollNumber = rollNumber;
	  }
          JsonProperty(value = "firstName")
	  public String getFirst_name() {
			return first_name;
	  public void setFirst_name(String first_name) {
			this.first_name = first_name;
	  }
         @JsonProperty(value = "lastName")
         public String getLast_name() {
			return last_name;
	  }
	 public void setLast_name(String last_name) {
			this.last_name = last_name;
	  }
}

@JsonProperty to Change index position in JSON

public class StudentDetail
{	
		@JsonProperty(value = "id")
		private int rollNumber;
		
		@JsonProperty(value = "firstName")
		private String first_name;
		
		@JsonProperty(value = "lastName" , index=1)
		private String last_name;
}

@JsonProperty to Default Value in JSON

@JsonProperty, defaultValue attribute not work with json core, it work with JSON binding while using with @Entity in JPA.

public class StudentDetail
{	
		@JsonProperty(value = "id")
		private int rollNumber;
		
		@JsonProperty(value = "firstName")
		private String first_name;
		
		@JsonProperty(value = "lastName" , defaultValue="Gupta", index=1)
		private String last_name;
}

 

Here you will see complete example of JSON properties name change and define index position for propertis.

Complete Example

public class StudentDetail
{	
		@JsonProperty(value = "id")
		private int rollNumber;
		
		@JsonProperty(value = "firstName")
		private String first_name;
		
		@JsonProperty(value = "middleName")
		private String middle_name;
		
		@JsonProperty(value = "lastName", index=1)
		private String last_name;

		public StudentDetail()
		{
			
		}
		//Getter and Setter

                //toString() method
}

Code to convert JSON to Java object

public class JsonPropertiesNameChange {
		public static void main(String[] args) {

			String json = 	"{\"id\" : 11,\"firstName\" : \"Saurabh\",\"lastName\" : \"Gupta\"}";

			System.out.println(json);
			try {
				// ObjectMapper new instance
				ObjectMapper objectMapper = new ObjectMapper();
				// convert json data to respective java object
				StudentDetail student = objectMapper.readValue(json, StudentDetail.class);
				// print java student java object
				System.out.println(student);
			} catch (JsonMappingException ex) {
				ex.printStackTrace();
			} catch (JsonGenerationException ex) {
				ex.printStackTrace();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}

Output


{"id" : 11,"firstName" : "Saurabh","lastName" : "Gupta"}
StudentDetail [rollNumber=11, firstName=Saurabh, lastName=Gupta]

References

https://github.com/FasterXML/jackson-annotations

You would like to see

Follow below link to learn more on JSON and  JSON issues solutions:

[Solved] com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `int` from String “C21”: not a valid Integer value


InvalidFormatException is subclass of MismatchedInputException. InvalidFormatException occurred because of bad formatting or format not match with the presepecified format of value to deserialize.

InvalidFormatException Example

The issue is passing type is String while deserialization expecting as Int.

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;

public class StudentDetail {
	private int rollNumber;
	private String firstName;
	private String lastName;

	//getter and setter of class
	}
import java.io.IOException;

import com.fasterxml.jackson.databind.ObjectMapper;

public class TestJacksonExample2 {

	public static void main(String[] args) {

	    String json="{\"rollNumber\":\"C21\" , \"firstName\":\"Saurabh\" , \"lastName\":\"Gupta\"}";

	    System.out.println(json);
		try
		{
	    ObjectMapper mapper = new ObjectMapper();
	    StudentDetail student= mapper.readValue(json, StudentDetail.class);
	    System.out.println(student);
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}

	}

}

InvalidFormatException Stacktrace


{"rollNumber":"C21" , "firstName":"Saurabh" , "lastName":"Gupta"}
com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `int` from String "C21": not a valid Integer value
 at [Source: (String)"{"rollNumber":"C21" , "firstName":"Saurabh" , "lastName":"Gupta"}"; line: 1, column: 15] (through reference chain: com.fiot.json.jackson.exceptions.StudentDetail["rollNumber"])
    at com.fasterxml.jackson.databind.exc.InvalidFormatException.from(InvalidFormatException.java:67)
    at com.fasterxml.jackson.databind.DeserializationContext.weirdStringException(DeserializationContext.java:1549)
    at com.fasterxml.jackson.databind.DeserializationContext.handleWeirdStringValue(DeserializationContext.java:911)
    at com.fasterxml.jackson.databind.deser.std.NumberDeserializers$IntegerDeserializer._parseInteger(NumberDeserializers.java:522)
    at com.fasterxml.jackson.databind.deser.std.NumberDeserializers$IntegerDeserializer.deserialize(NumberDeserializers.java:474)
    at com.fasterxml.jackson.databind.deser.std.NumberDeserializers$IntegerDeserializer.deserialize(NumberDeserializers.java:452)
    at com.fasterxml.jackson.databind.deser.impl.FieldProperty.deserializeAndSet(FieldProperty.java:138)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:288)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3004)
    at com.fiot.json.jackson.exceptions.TestJacksonExample2.main(TestJacksonExample2.java:18)

Solutions

Pass value as the compatible type, here in this case number value roll number can’t accept as a text string with an alphanumeric.

In such cases, if your organization is using rollNumber as alphanumeric then convert int to String to make compatible. or ask your client application to pass the value of rollNumber as an int value.

References

https://fasterxml.github.io/jackson-databind/javadoc/2.9/com/fasterxml/jackson/databind/exc/InvalidFormatException.html

You would like to see

Follow below link to learn more on JSON and  JSON issues solutions:

Solved] com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.util.Date` from String “MM/dd/yyyy”: not a valid representation for date format


InvalidFormatException is subclass of MismatchedInputException. InvalidFormatException occurred because of bad formatting or format not match with the prespecified format of value to deserialize.

InvalidFormatException Example

This example throwing InvalidFormatException because JSONis having the format “MM/dd/yyyy” for dob which is not compatible with standard date format for deserializations. Below is a standard format for a date as JACKSON support:

  • yyyy-MM-dd’T’HH:mm:ss.SSSZ
  • yyyy-MM-dd’T’HH:mm:ss.SSS
  • EEE, dd MMM yyyy HH:mm:ss zzz
  • yyyy-MM-dd
import java.util.Date;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.JsonFormat;

public class StudentDetail {
	private int rollNumber;
	private String firstName;
	private String lastName;
	private Date dob;
	//getter and setter of class
	}
import java.io.IOException;

import com.fasterxml.jackson.databind.ObjectMapper;

public class TestJacksonExample2 {

	public static void main(String[] args) {

	    String json="{\"rollNumber\":21 , \"firstName\":\"Saurabh\" , \"lastName\":\"Gupta\",  \"dob\":\"12/13/1985\"}";

	    System.out.println(json);
		try
		{
	    ObjectMapper mapper = new ObjectMapper();
	    StudentDetail student= mapper.readValue(json, StudentDetail.class);
	    System.out.println(student);
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}

	}

}

InvalidFormatException Stacktrace


com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.util.Date` from String "12/13/1985": not a valid representation (error: Failed to parse Date value '12/13/1985': Cannot parse date "12/13/1985": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))
 at [Source: (String)"{"rollNumber":21 , "firstName":"Saurabh" , "lastName":"Gupta",  "dob":"12/13/1985"}"; line: 1, column: 71] (through reference chain: com.fiot.json.jackson.exceptions.StudentDetail["dob"])
    at com.fasterxml.jackson.databind.exc.InvalidFormatException.from(InvalidFormatException.java:67)
    at com.fasterxml.jackson.databind.DeserializationContext.weirdStringException(DeserializationContext.java:1549)
    at com.fasterxml.jackson.databind.DeserializationContext.handleWeirdStringValue(DeserializationContext.java:911)
    at com.fasterxml.jackson.databind.deser.std.StdDeserializer._parseDate(StdDeserializer.java:524)
    at com.fasterxml.jackson.databind.deser.std.StdDeserializer._parseDate(StdDeserializer.java:467)
    at com.fasterxml.jackson.databind.deser.std.DateDeserializers$DateBasedDeserializer._parseDate(DateDeserializers.java:195)
    at com.fasterxml.jackson.databind.deser.std.DateDeserializers$DateDeserializer.deserialize(DateDeserializers.java:285)
    at com.fasterxml.jackson.databind.deser.std.DateDeserializers$DateDeserializer.deserialize(DateDeserializers.java:268)
    at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:129)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:288)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)

Solutions

  1. Pass date format for JSON as the standard one for deserializations.
    • yyyy-MM-dd’T’HH:mm:ss.SSSZ
    • yyyy-MM-dd’T’HH:mm:ss.SSS
    • EEE, dd MMM yyyy HH:mm:ss zzz
    • yyyy-MM-dd
  2. Use annotation @JsonFormat as below to support some other new date format.
    public class StudentDetail {
    	private int rollNumber;
    	private String firstName;
    	private String lastName;
    	@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MM/dd/yyyy")
    	private Date dob;
    	//getter and setter of class
    	}
    

Preferences

https://fasterxml.github.io/jackson-databind/javadoc/2.9/com/fasterxml/jackson/databind/exc/InvalidFormatException.html

You would like to see

Follow below link to learn more on JSON and  JSON issues solutions:

[Solved] com.fasterxml.jackson.databind.exc. InvalidDefinitionException: No serializer found for class ABC and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)


InvalidDefinitionException is an intermediate exception which is used as the base class for all JsonMappingExceptions that occurred due to problems with target type definition. Generally a problem with properties or annotations used on a class.

Exception Example

Here this InvalidDefinitionException is occurring because of StudentDetail class is not having any getter and setters.  That’s what while the time of deserialization found bean as empty.

public class StudentDetail {
	private int rollNumber;
	private String firstName;
	private String lastName;
	public StudentDetail(int rollNumber, String firstName, String lastName) {
		super();
		this.rollNumber = rollNumber;
		this.firstName = firstName;
		this.lastName = lastName;
	}
import java.io.IOException;

import com.fasterxml.jackson.databind.ObjectMapper;

public class TestJacksonExample3 {

	public static void main(String[] args) {

		try
		{
		StudentDetail student=new StudentDetail(10011,"Saurabh","Gupta");
	    ObjectMapper mapper = new ObjectMapper();
	    //convert java object to JSON
	    String json=mapper.writeValueAsString(student);
	    System.out.println(json);
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}

	}

}

Exception Stacktrace


com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class com.fiot.json.jackson.exceptions.StudentDetail and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)
    at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:77)
    at com.fasterxml.jackson.databind.SerializerProvider.reportBadDefinition(SerializerProvider.java:1191)
    at com.fasterxml.jackson.databind.DatabindContext.reportBadDefinition(DatabindContext.java:313)
    at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.failForEmpty(UnknownSerializer.java:71)
    at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.serialize(UnknownSerializer.java:33)
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider._serialize(DefaultSerializerProvider.java:480)
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:319)
    at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:3905)
    at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:3219)
    at com.fiot.json.jackson.exceptions.TestJacksonExample3.main(TestJacksonExample3.java:17)

Solutions

There is a couple of solution to resolve this issue:

  1. If you have the option to edit source, add getter and setter of properties of the class.
  2. On class, level add annotation @JsonAutoDetect(fieldVisibility = Visibility.ANY) to StudentDetail class to resolve this issue.
    @JsonAutoDetect(fieldVisibility = Visibility.ANY)
    public class StudentDetail {
    	private int rollNumber;
    	private String firstName;
    	private String lastName;
    	public StudentDetail(int rollNumber, String firstName, String lastName) {
    		super();
    		this.rollNumber = rollNumber;
    		this.firstName = firstName;
    		this.lastName = lastName;
    	}
    
  3. We can resolve this issue by setting configuring of ObjectMapper visibility for fields as Visibility.ANY.
    try
    	{
    	StudentDetail student=new StudentDetail(10011,"Saurabh","Gupta");
    	ObjectMapper mapper = new ObjectMapper();
    	mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
    	//convert java object to JSON
    	String json=mapper.writeValueAsString(student);
    	System.out.println(json);
    		}
    		catch(IOException ex)
    		{
    			ex.printStackTrace();
    		}
    		catch(Exception ex)
    		{
    			ex.printStackTrace();
    		}
    
    	}
    

You would like to see

Follow below link to learn more on JSON and  JSON issues solutions:

JSON Overview


JSON (JavaScript Object Notation) is a lightweight, language-independent, text-based data storage and data-interchange format to sharing between systems.

Below are some properties make JSON an ideal data-interchange language:

  • JSON is “self-describing” and easy for humans to read and write.
  • JSON is text, written with JavaScript object notation.
  • JSON represent values in form of key/value pairs.
  • JSON is easy for API’s to parse and generate.
  • JSON is a text format that is supported by many languages because of language-independent

Points to remember

The JSON file extension is “.json”
The JSON text MIME type is “application/json”.

Why use JSON?

There are so many reasons to use JSON:

  1. JSON represents values in form of key/value pairs which is easy to understand and supported by most programming languages For Ex: C, C++, C#, Java, JavaScript, Perl, Python, and many others.
  2. The JSON format is text, it can easily exchange browser to and from a server,
  3. Current enterprise application uses JSON for communications to the server with REST services, Communication to the server with Ajax call, convert Javascript object to JSON or vice versa.
  4. JSON extensively used by NoSQL database to store records as JSON documents. For Ex: MongoDB, Oracle NoSQL Database, and Oracle Berkeley DB.
  5. Traditional relational databases constantly gaining more JSON capabilities like PostgreSQL, Oracle, etc. supports JSON data for certain features such as transactions, indexing, declarative querying, and views.

JSON Example

You can refer below JSON  object to represent Student Detail. Corresponding is a description of the representation of each field in JSON with respect to the data type.

JSON Data Type & Syntax

Student JSON Object

Above JSON is generated with respect to below Student JAVA object. You can follow below link to know about JSON supported Data Type and Syntax.

Student Java Object

The same Student and JSON object will refer in the subsequent example related to JAVA for more JSON + JAVA handling example.

JAVA JSON API’s

Below is the list of the library that developed by java open source community to handle (JAVA +JSON) development.

  • JACKSON
  • GSON
  • Boon
  • JSON.org

Follow below link to know in-depth knowledge of JSON parsers and in which case should be used specifically.

JSON Parsers

You would like to see

Follow below link to learn more on JSON and  JSON issues solutions:

 

JSON Parsers


JSON (JavaScript Object Notation) is most popular for NoSQL data storage, data exchange format between browsers and web servers and latest framework also use for communication over networks.

For Example :

  • All latest browsers natively support parse JSON data to java script to display over page.
  • REST Service support one of MediaType is JSON to exchange data between browsers or client application to servers where these REST Services are deploy.
  • Some latest framework like Elasticsearch, Logstash, Kibana, Kafka ,Filebeat etc. are used JSON for internal storage and data exchange over network between servers.

All these above cases, JSON data language independent feature provides communication compatibility between different type frameworks and servers. All these frameworks and servers implemented by one of computer language which provides JSON API’s by internally or consumed third party library for parsing and generation.

Here we will focus mainly on Java based JSON APIs which provide various choices for parsing and JSON generation on different cases from JAVA objects.

The Java Open Source Community developed some JSON APIs which offers more choices and flexibility to work with JSON. Here is list of some well-known JSON APIS:

  • Jackson
  • GSON
  • Boon
  • JSON.org

See also : Serialization and Deserialization of JSON to/from JAVA.

JACKSON

Jackson is most popular Java JSON APIs which provide several choices to work with JSON. It contains two different parsers:

  • JsonParser : This is pull parser, which parse one token at a time. These token generated by JsonGenerator.
  • JsonMapper : This parser is use convert customize JSON to/from JAVA object. It also parse data in tree model.

You can follow this link to more detail about Jackson JSON APIs : https://github.com/FasterXML/jackson

GSON

GSON provides flexible Java JSON API developed by Google. GSON APIs are able to work with arbitrary Java objects including pre-existing objects that you do not have source code. It also supports for handling complex objects with generics and deep inheritance. GSON is having three different parsers for JSON Java APIS:

  • Gson class : It can parse JSON into custom Java objects.
  • JsonReador : It’s pull JSON parser, which parse one token at a time.
  • JsonParser : It’s parser JSON into a tree structure of GSON specific Java Objects.

You can follow this link to more detail about GSON JSON APIs : https://github.com/google/gson

Boon

Boon is a standard JSON API in Groovy . It is similar to JACKSON but not only apecific for Java JSON API. It’s complete tool kit to working with data, file process and REST services etc. Boon contains the following Java JSON parsers:

  • ObjectMapper :This parser is use to parse JSON into custom objects and Java Maps.

You can follow this link to more detail about BOON JSON APIs : https://github.com/boonproject/boon

JSON.org

JSON.org provides the first JSON API developed for Java. It’s easy to use but not flexible and fast as compared to others  Java JSON open source APIs.

As I recommend if your application is too old and using this API then only go with it otherwise you can switch with others above Java JSON APIs.

You can follow this link to more detail about JSON.org JSON APIs : https://github.com/douglascrockford/JSON-java

Here, In my further posts for JSON I will focus on JACKSON and GSON because that are most known JSON APIs used by developers.

You would like to see

Follow below link to see more about JSON Tutorial and JSON issues Solutions:

JSON Data Types & Syntax


In previous post, JSON Overview explain about background of JSON, reason to use JSON with data exchange web page to/from servers and No SQL database storage with JSON. Now here we discuss about to JSON supporting Data Types and JSON syntax representation with respect to each data types.

JSON Object Syntax

JSON is language independent because of universal data format structures which is almost support by all modern languages. JSON Object follows below syntax for handling different type of data:

  • JSON object are surrounded with curly braces ({}).
  • JSON object data are written in key/value pairs to represent an object, record, Map, list, array etc.
  • JSON key and value are separated by a colon.
  • JSON objects each key/value pair is separated by a comma (,).
  • JSON keys are strings, written in double quotes(“”) and values can be any data type supported by JSON.
  • JSON Object for list of values (an array, vector, list or sequence) are store in form of array and represent as square braces ([]).

JSON Supported Data Types

JSON data can be represent with following data types:

  • a string
  • a number
  • an object (JSON object)
  • an array
  • a boolean
  • null

JSON Example

Here is Student detail JSON representation which considers all the above data types and Syntax rules. This example will help you to understand JSON representation with respect to each type of data.

Student JSON Object

JSON for String Value

In JSON string values are represented in double quote (“”);

{
	"firstName" : "Saurabh",
	"lastName" : "Gupta"
}

JSON for Number Value

In JSON, number values such as (integer, float, double) values are not required  double quotes.

{"rollNumber" : 11}

JSON for Boolean Value

In JSON, to represent Boolean allowed values are true/false and not required double quotes.

{"permanent" : false}

JSON for an Array

In JSON, Array values are represent in square braces ([]) as shown for cities and phoneNumbers.

{
"phoneNumbers" : [ 2233445566, 3344556677 ],
"cities" : [ "Dallas", "San Antonio", "Irving" ]
}

JSON for a Map

In JSON, Map represent as object with in curly braces and each key and value of Map write same way as write properties of Object.

{
"properties" : {
    "play" : "Badminton",
    "interst" : "Math",
    "age" : "34 years"
  }
}

JSON for an Object

In JSON, Object represent with in curly braces. Here address is internal object of student.

{
	"address" : {
		"addressLine" : "Lake Union Hill Way",
		"city" : "Atlanta",
		"zipCode" : 50005
  }
}

JSON for Null

In JSON, null values are write as below.

{"middleName" : null}

Now you have learned about JSON supported data types and there representation in JSON. In next post you will learn about JSON parsers for serialization and deserialization to/from Java objects. JSON Parsers

You would like to see

Follow below link to learn more on JSON and  JSON issues solutions:

 

[Solved] com.fasterxml.jackson.databind.exc. MismatchedInputException: Cannot deserialize instance of `XYZ` out of START_ARRAY token


MismatchedInpuException is base class for all JsonMappingExceptions. It occurred when input is not mapping with target definition or mismatch between as required for fulfilling the deserialization. This exception is used for some input problems, but in most cases, there should be more explicit subtypes to use.

Example of MismatchedInputException

Here MismatchedInpuException issue is happening because of type mismatch because passing JSON as an array of StudentDetail while deserialization is mapped for single StudentDetail object.

public class StudentDetail {
	private int rollNumber;
	private String firstName;
	private String lastName;

	//getter and setter of class
}
import java.io.IOException;

import com.fasterxml.jackson.databind.ObjectMapper;

public class TestJacksonExample2 {

	public static void main(String[] args) {
	    String json=" ["
	    				+ "{\"rollNumber\":21 , \"firstName\":\"Saurabh\" , \"lastName\":\"Gupta\"}, "
	    				+ "{\"rollNumber\":22 , \"firstName\":\"Abhishek\" , \"lastName\":\"Garg\"}"
	    		+ "]";

	    System.out.println(json);
		try
		{
	    ObjectMapper mapper = new ObjectMapper();
		//issue is here
	    StudentDetail student= mapper.readValue(json, StudentDetail.class);
	    System.out.println(student);
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}

	}

}

MismatchedInputException Stacktrace


 [{"rollNumber":21 , "firstName":"Saurabh" , "lastName":"Gupta"}, {"rollNumber":22 , "firstName":"Abhishek" , "lastName":"Garg"}]
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `com.fiot.json.jackson.exceptions.StudentDetail` out of START_ARRAY token
 at [Source: (String)" [{"rollNumber":21 , "firstName":"Saurabh" , "lastName":"Gupta"}, {"rollNumber":22 , "firstName":"Abhishek" , "lastName":"Garg"}]"; line: 1, column: 2]
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1343)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1139)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1093)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromArray(BeanDeserializerBase.java:1461)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:185)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:161)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3004)
    at com.fiot.json.jackson.exceptions.TestJacksonExample2.main(TestJacksonExample2.java:22)

Solutions

To resolve this issue, change the type from StudentDetail to as array StudentDetail[]

public static void main(String[] args) {
	    String json=" ["
	    				+ "{\"rollNumber\":21 , \"firstName\":\"Saurabh\" , \"lastName\":\"Gupta\"}, "
	    				+ "{\"rollNumber\":22 , \"firstName\":\"Abhishek\" , \"lastName\":\"Garg\"}"
	    		+ "]";
	    System.out.println(json);
		try
		{
	    ObjectMapper mapper = new ObjectMapper();
		//Convereted to Type as array
	    StudentDetail[] students= mapper.readValue(json,  StudentDetail[].class );
	    System.out.println(students);
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}

	}

References

https://fasterxml.github.io/jackson-databind/javadoc/2.9/com/fasterxml/jackson/databind/exc/MismatchedInputException.html

You would like to see

Follow below link to learn more on JSON and  JSON issues solutions:

[Solved] com.fasterxml.jackson.databind.exc. MismatchedInputException: Root name ‘ABC’ does not match expected (‘XYZ’) for type [simple type, class ClassName]


MismatchedInpuException is base class for all JsonMappingExceptions. It occurred when input is not mapping with target definition or mismatch between as required for fulfilling the deserialization. This exception is used for some input problems, but in most cases, there should be more explicit subtypes to use.

Example of MismatchedInputException

When we deserialize JSON data with property DeserializationFeature.UNWRAP_ROOT_VALUE then it will check root name as className. Here in this case class name “StudentDetail” while passing JSON having a root name as “student” that’s what throwing MismatchedInputException because of mismatch of root name.

public class StudentDetail {
	private int rollNumber;
	private String firstName;
	private String lastName;
	//getter and setter of class
	}
import java.io.IOException;

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

public class TestJacksonExample2 {

	public static void main(String[] args) {
	    String json="{\"student\":{\"rollNumber\":21 , \"firstName\":\"Saurabh\" , \"lastName\":\"Gupta\"}}";

		try
		{
	    ObjectMapper mapper = new ObjectMapper();
	    //Before  deserialize this properties will unwrap the json.
	    mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);

	    StudentDetail student= mapper.readValue(json, StudentDetail.class);
	    System.out.println(student);
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}

	}

Stacktrace of MismatchedInputException


com.fasterxml.jackson.databind.exc.MismatchedInputException: Root name 'student' does not match expected ('StudentDetail') for type [simple type, class com.fiot.json.jackson.exceptions.StudentDetail]
 at [Source: (String)"{"Student":{"rollNumber":21 , "firstName":"Saurabh" , "lastName":"Gupta"}}"; line: 1, column: 2]
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59)
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1356)
    at com.fasterxml.jackson.databind.ObjectMapper._unwrapAndDeserialize(ObjectMapper.java:4087)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4011)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3004)
    at com.fiot.json.jackson.exceptions.TestJacksonExample2.main(TestJacksonExample2.java:19)

Solution

To resolve this issue use the annotation @JsonRootName as below so that overwrite root name as “student” on default root name (StudentDetail)

@JsonRootName(value = "student")
public class StudentDetail {
	private int rollNumber;
	private String firstName;
	private String lastName;
	//getter and setter of class
	}

You would like to see

Follow below link to see more JSON issues solutions:

JSON Issues Solutions

References

https://fasterxml.github.io/jackson-databind/javadoc/2.9/com/fasterxml/jackson/databind/exc/MismatchedInputException.html

[Solved] com.fasterxml.jackson.core.JsonParseException: Unexpected character (”’ (code 39)): was expecting double-quote to start field name


JsonParseException is subclass of JsonProcessingException. This exception occurred because parsing issues or non-well-formed content because of not fulling JSON syntax specification.

JsonParserException Example

Here JSonParserException occurred because not fulfilling the syntax specification because properties name  and String values in JSON should always write in double-quotes (“);

public class StudentDetail {
	private int rollNumber;
	private String firstName;
	private String lastName;
	//getter and setter of class
	}
public class TestJacksonExample2 {

	public static void main(String[] args) {

	    String json="{\'rollNumber\':21 , \'firstName\':\'Saurabh\' , \'lastName\':\'Gupta\'} ";

	    System.out.println(json);
		try
		{
	    ObjectMapper mapper = new ObjectMapper();
	    StudentDetail student= mapper.readValue(json, StudentDetail.class);
	    System.out.println(student);
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}

	}

}

Exception Stacktrace


{'rollNumber':21 , 'firstName':'Saurabh' , 'lastName':'Gupta'} 
com.fasterxml.jackson.core.JsonParseException: Unexpected character (''' (code 39)): was expecting double-quote to start field name
 at [Source: (String)"{'rollNumber':21 , 'firstName':'Saurabh' , 'lastName':'Gupta'} "; line: 1, column: 3]
    at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1804)
    at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:693)
    at com.fasterxml.jackson.core.base.ParserMinimalBase._reportUnexpectedChar(ParserMinimalBase.java:591)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._handleOddName(ReaderBasedJsonParser.java:1767)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser.nextToken(ReaderBasedJsonParser.java:692)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3004)
    at com.fiot.json.jackson.exceptions.TestJacksonExample2.main(TestJacksonExample2.java:18)

Solutions

There are two solutions to resolve this issue:

  1. Send JSON in a standard format as with properties name and String value in double-quotes.
     String json="{\"rollNumber\":21 , \"firstName\":\"Saurabh\" , \"lastName\":\"Gupta\"}";
    
  2. By configuring the ObjectMapper to allow single quotes as below:
    public static void main(String[] args) {
    String json="{\'rollNumber\':21 , \'firstName\':\'Saurabh\' , \'lastName\':\'Gupta\'} ";
    
    System.out.println(json);
    try
       {
    	//add to allow single quote
    	JsonFactory factory = new JsonFactory();
    	factory.enable(Feature.ALLOW_SINGLE_QUOTES);
    	ObjectMapper mapper = new ObjectMapper(factory);
    
    	StudentDetail student= mapper.readValue(json, StudentDetail.class);
    	System.out.println(student);
        }
     catch(IOException ex)
    {
    	ex.printStackTrace();
    }
    catch(Exception ex)
    {
    	ex.printStackTrace();
    }
    }
    

You would like to see

Follow below link to see more JSON issues solutions:

JSON Issues Solutions

References

https://fasterxml.github.io/jackson-core/javadoc/2.2.0/com/fasterxml/jackson/core/JsonParseException.html

[Solved] com.fasterxml.jackson.core.JsonParseException: Unexpected character (‘{‘ (code 123)): was expecting double-quote to start field name


JsonParseException is subclass of JsonProcessingException. This exception occurred because parsing issues or non-well-formed content because of not fulling JSON syntax specification.

JsonParserException Example

Here JSonParserException occurred because not fulfilling the syntax specification because two curly brackets ({) used continuously

public class StudentDetail {
	private int rollNumber;
	private String firstName;
	private String lastName;

	//getter and setter of class
}
public static void main(String[] args) {

	    String json="{{\"rollNumber\":21 , \"firstName\":\"Saurabh\" , \"lastName\":\"Gupta\"}} ";

	    System.out.println(json);
		try
		{
	    ObjectMapper mapper = new ObjectMapper();
	    StudentDetail student= mapper.readValue(json, StudentDetail.class);
	    System.out.println(student);
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}

JsonParserException Stacktrace


 {{"rollNumber":21 , "firstName":"Saurabh" , "lastName":"Gupta"}} 
com.fasterxml.jackson.core.JsonParseException: Unexpected character ('{' (code 123)): was expecting double-quote to start field name
 at [Source: (String)" {{"rollNumber":21 , "firstName":"Saurabh" , "lastName":"Gupta"}} "; line: 1, column: 4]
    at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1804)
    at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:693)
    at com.fasterxml.jackson.core.base.ParserMinimalBase._reportUnexpectedChar(ParserMinimalBase.java:591)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._handleOddName(ReaderBasedJsonParser.java:1767)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser.nextToken(ReaderBasedJsonParser.java:692)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:155)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3004)
    at com.fiot.json.jackson.exceptions.TestJacksonExample2.main(TestJacksonExample2.java:23)

Solutions

To fix this issue remove one level of the curly bracket from start and end so that fulfill JSON specification. The correct JSON for this example would be :

 String json="{\"rollNumber\":21 , \"firstName\":\"Saurabh\" , \"lastName\":\"Gupta\"}";

As per JSON specification after curly bracket ({) only allow double quote for showing properties name or square bracket ([) if need to show set of objects or values.

You would like to see

Follow below link to see more JSON issues solutions:

JSON Issues Solutions

References

https://fasterxml.github.io/jackson-core/javadoc/2.2.0/com/fasterxml/jackson/core/JsonParseException.html

[Solved] com.fasterxml.jackson.databind.exc. InvalidDefinitionException: Cannot construct instance of `XYZ` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)


InvalidDefinitionException is intermediate exception which is used as the base class for all JsonMappingExceptions that occurred due to problems with target type definition. Generally a problem with properties or annotations used on a class.

Example of InvalidDefinitionException

In this given example deserialing String JSON to Student object. Here Student class is not having default constructor that’s causing issue as “No able to construct object as no default constructor found”


public class Student {
private int rollNumber;
private String firstName;
private String lastName;

public Student(int rollNumber, String firstName, String lastName)
{
this.rollNumber=rollNumber;
this.firstName=firstName;
this.lastName=lastName;
}
// getter and setter of class
}
import java.io.IOException;

import com.fasterxml.jackson.databind.ObjectMapper;

public class TestJacksonExample {

public static void main(String[] args) {

   String json="{\"rollNumber\":21 , \"firstName\":\"Saurabh\" , \"lastName\":\"Gupta\"}";

try
{
   ObjectMapper mapper = new ObjectMapper();
   Student student= mapper.readValue(json, Student.class);
   System.out.println(student);
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(Exception ex)
{
ex.printStackTrace();
}

}

Stacktrace of InvalidDefinitionException


com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.fiot.json.jackson.exceptions.Student` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: (String)"{"rollNumber":21 , "firstName":"Saurabh" , "lastName":"Gupta"}"; line: 1, column: 2]
    at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:67)
    at com.fasterxml.jackson.databind.DeserializationContext.reportBadDefinition(DeserializationContext.java:1452)
    at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1028)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1297)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:326)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:159)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3004)
    at com.fiot.json.jackson.exceptions.TestJacksonExample.main(TestJacksonExample.java:18)

Solutions

To solution of this issue just add a default constructor as below


public class Student {
	private int rollNumber;
	private String firstName;
	private String lastName;
        //default constructor
	public Student()
	{
	 super();
	}
	public Student(int rollNumber, String firstName, String lastName)
	{
		this.rollNumber=rollNumber;
		this.firstName=firstName;
		this.lastName=lastName;
	}
	// getter and setter of class
	}
	

Note:

Jackson looks for POJO class for deserialization. As per definition of POJO (Plain Old Java Object) is the class with out any restriction, having getter and setter methods, if required can also implement object class methods like equals(), toString() etc.

You would like to see

Follow below link to see more JSON issues solutions:

JSON Issues Solutions

References

https://fasterxml.github.io/jackson-databind/javadoc/2.9/com/fasterxml/jackson/databind/exc/InvalidDefinitionException.html

[Solved] com.fasterxml.jackson.databind.exc. InvalidDefinitionException: Cannot construct instance of `XYZ` (no Creators, like default construct, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information


InvalidDefinitionException is an intermediate exception which is used as the base class for all JsonMappingExceptions that occurred due to problems with target type definition. Generally a problem with properties or annotations used on a class.

Example of InvalidDefinitionException

Here Publication class is abstract that’s causing issues because we can’t directly create an instance of an abstract class. Here at the time  of JSON deserialization to author object not able to create an instance of Publication class.

public class Author {
	  private String name;
	  public Publication publication;

	  public Author()
	  {

	  }

	  //getter and setter of properties
	}

	public abstract class Publication {
	public String title;

	public Publication() {

	}
	// getter and setter of properties
}
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
<span id="mce_SELREST_start" style="overflow: hidden; line-height: 0;"></span>
public abstract class Publication {
	public String title;

	public Publication() {

	}
	// getter and setter of properties
}
import java.io.IOException;

import com.fasterxml.jackson.databind.ObjectMapper;

public class TestJacksonExample {

public static void main(String[] args) {
String json = "{\"name\":\"Saurabh Gupta\",\"publication\":{\"title\":\"Facing Issues On IT\",\"type\":\"Drama\" }}";

try
{
   ObjectMapper mapper = new ObjectMapper();
   Author author= mapper.readValue(json, Author.class);
   System.out.println(author);
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}

Stacktrace of InvalidDefinitionException


com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.fiot.json.jackson.exceptions.Publication` (no Creators, like default construct, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
 at [Source: (String)"{"name":"Saurabh Gupta","publication":{"title":"Facing Issues On IT"}}"; line: 1, column: 39] (through reference chain: com.fiot.json.jackson.exceptions.Author["publication"])
    at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:67)
    at com.fasterxml.jackson.databind.DeserializationContext.reportBadDefinition(DeserializationContext.java:1452)
    at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1028)
    at com.fasterxml.jackson.databind.deser.AbstractDeserializer.deserialize(AbstractDeserializer.java:265)
    at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:129)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:288)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3004)
    at com.fiot.json.jackson.exceptions.TestJacksonExample.main(TestJacksonExample.java:17)

Solutions

As a solution to the current issue, Not declare Publication class as abstract because we can’t directly create an instance of an abstract class only allowed instance through subclass. 

Recommend Solution

We can solve this problem by using simple @JsonDeserialize on the abstract class as mentioned as a subtype.

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;

//@JsonDeserialize(as = Book.class)
public abstract class Publication {
	public String title;

	public Publication() {

	}
	// getter and setter of class
}

If abstract class having more than one subtype, then mentioned all the classes as SubTypes.

@JsonSubTypes(
{
	@Type(value = Book.class, name = "book"),
	@Type(value = Magzine.class, name = "magzine"),
        @Type(value = Comics.class, name = "comics")
})
public abstract class Publication {
}

Note:

Jackson looks for POJO class for deserialization. As per the definition of POJO (Plain Old Java Object) is the class without any restriction, having getter and setter methods, if required can also implement object class methods like equals, toString(), etc.

References

https://fasterxml.github.io/jackson-databind/javadoc/2.9/com/fasterxml/jackson/databind/exc/InvalidDefinitionException.html

You would like to see

Follow below link to learn more on JSON and  JSON issues solutions:

[Solved] com.fasterxml.jackson.databind.exc. MismatchedInputException: Cannot construct instance of `XYZ` (although at least one Creator exists): can only instantiate non-static inner class by using default, no-argument constructor


MismatchedInpuException is base class for all JsonMappingExceptions. It occurred when input is not mapping with target definition or mismatch between as required for fulfilling the deserialization. This exception is used  for some input problems, but in most cases there should be more explicit subtypes to use.

MismatchedInputException Example

Here MismatchedInputException is occurring because of StudentDetail class define as private but Jackson always looks for class POJO for deserialization.

package com.fiot.json.jackson.annotations;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fiot.json.jackson.pojo.Address;
import com.fiot.json.jackson.pojo.Student;

public class JsonIgnoreUnknownProperties {

	public static void main(String[] args) {

	String json="	{\"id\" : 11,\"firstName\" : \"Saurabh\",\"middleName\" : \"Kumar\",\"lastName\" : \"Gupta\"}";

	System.out.println(json);
	try {
		// ObjectMapper new instance
		ObjectMapper objectMapper = new ObjectMapper();
		//convert json data to respective java object
		StudentDetail student = objectMapper.readValue(json, StudentDetail.class);
		// print java student java object
		System.out.println(student);
	} catch (JsonMappingException ex) {
		ex.printStackTrace();
	} catch (JsonGenerationException ex) {
		ex.printStackTrace();
	} catch (IOException ex) {
		ex.printStackTrace();
	}
	}
	@JsonIgnoreProperties(ignoreUnknown = true)
	private class StudentDetail
	{
			@JsonProperty(value = "id")
			private int rollNumber;

			@JsonProperty(value = "firstName")
			private String firstName;

			@JsonProperty(value = "lastName")
			private String lastName;

			//Getter and Setter

	}
}

Stacktrace of Exception


com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.fiot.json.jackson.annotations.JsonIgnoreUnknownProperties$StudentDetail` (although at least one Creator exists): can only instantiate non-static inner class by using default, no-argument constructor
 at [Source: (String)"  {"id" : 11,"firstName" : "Saurabh","middleName" : "Kumar","lastName" : "Gupta",}"; line: 1, column: 3]
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1343)
    at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1032)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1294)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:326)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:159)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3004)
    at com.fiot.json.jackson.annotations.JsonIgnoreUnknownProperties.main(JsonIgnoreUnknownProperties.java:27)

Solutions

As solution of this exception for current issue define StudentClass as public because Jackson looks for POJO class for deserialization.

As per definition of POJO (Plain Old Java Object) is the class with out any restriction, having getter and setter methods, if required can also implement object class methods like equals, toString() etc.

You would like to see

Follow below link to see more JSON issues solutions:

JSON Issues Solutions

References

https://stackoverflow.com/questions/43923914/com-fasterxml-jackson-databind-exc-mismatchedinputexception-can-not-deserialize

[Solved] com.fasterxml.jackson.databind.exc. UnrecognizedPropertyException: Unrecognized field XYZ (class ABC), not marked as ignorable (X known properties: ])


UnrecognizedPropertyException occurred on time of deserialization of JSON. When no match of getter and setter method found for properties specified in JSON.

Jackson ObjectMapper required POJO class with respect to JSON to convert JSON to JAVA object.

UnrecognizedPropertyException Example

In this example to convert JSON to JAVA object , Student  class is not having any getter and setter method as basic requirement of POJO class. That’s causing the issue and throw UnrecognizedPropertyException.

public class Student {
private int rollNumber;
private String firstName;
private String lastName;
//no getter and setter for above properties
}
import java.io.IOException;

import com.fasterxml.jackson.databind.ObjectMapper;

public class TestJacksonExample {

public static void main(String[] args) {
   String json="{\"rollNumber\":21 , \"firstName\":\"Saurabh\" , \"lastName\":\"Gupta\"}";
try
{
   ObjectMapper mapper = new ObjectMapper();
   mapper.reader().forType(Student.class).readValue(json);
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(Exception ex)
{
ex.printStackTrace();
}

}

}

UnrecognizedPropertyException Stacktrace


com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "rollNumber" (class com.fiot.json.jackson.exceptions.Student), not marked as ignorable (0 known properties: ])
 at [Source: (String)"{"rollNumber":21 , "firstName":"Saurabh" , "lastName":"Gupta"}"; line: 1, column: 17] (through reference chain: com.fiot.json.jackson.exceptions.Student["rollNumber"])
at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:61)
at com.fasterxml.jackson.databind.DeserializationContext.handleUnknownProperty(DeserializationContext.java:823)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:1153)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1589)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownVanilla(BeanDeserializerBase.java:1567)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:294)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)
at com.fasterxml.jackson.databind.ObjectReader._bindAndClose(ObjectReader.java:1611)
at com.fasterxml.jackson.databind.ObjectReader.readValue(ObjectReader.java:1219)
at com.fiot.json.jackson.exceptions.TestJacksonExample.main(TestJacksonExample.java:15)

Solutions

There are couple of solutions to solve this issue:

    1. Jackson work with POJO classes, so write getter and setter of class properties to resolve above issue.
    2. Write @JsonIgnoreProperties(ignoreUnknown = true) on class level so that If any unknown property will receive in JSON that is not match with POJO object getter and setter then time of deserialization will ignore and no any exception occurred.

For example : When you replace above JSON with this one as it’s having new property middleName which is not match with properties in Student POJO object. This will again through same exception with different exception message.

String json="{\"rollNumber\":21 , \"firstName\":\"Saurabh\" , \"lastName\":\"Gupta\", \"middleName\":\"Kumar\"}";

No exception occurred when add annotation as @JsonIgnoreProperties(ignoreUnknown = true)

@JsonIgnoreProperties(ignoreUnknown = true)
public class Student {
private int rollNumber;
private String firstName;
private String lastName;
//write getter and setter of properties
}
  1. To resolve this issue, you can also disable ObjectMapper checking for unknown properties.
    ObjectMapper mapper = new ObjectMapper();
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    

You would like to see

Follow below link to see more JSON issues solutions:

JSON Issues Solutions

[Solved] java.nio.file.NoSuchFileException: XYZ


NoSuchFileException occurred when trying to attempt access a file or directory which is not exist in given location.

NoSuchFileException is sub class of FileSystemException. This exception  introduced in Java 7.

Example for NoSuchFileException

This example is throwing NoSuchFileException because trying to access a file student_data.json which is not exist on default location.

package com.fiot.json.jackson;

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;
import com.fiot.json.jackson.pojo.Student;

public class ConvertJsonToArrayList {

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

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

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

	}

}

Exception Stacktrace


java.nio.file.NoSuchFileException: student_data.json
    at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
    at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
    at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
    at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(Unknown Source)
    at java.nio.file.Files.newByteChannel(Unknown Source)
    at java.nio.file.Files.newByteChannel(Unknown Source)
    at java.nio.file.Files.readAllBytes(Unknown Source)
    at com.fiot.json.jackson.ConvertJsonToArrayList.main(ConvertJsonToArrayList.java:18)

Solutions

There are couple of solutions to handle such situations:

  1. Use fully qualified file path such as “C:/data/student_data.json” but that will help only when your program is going to run on local machine. While working with enterprise application always use relative paths.
  2. If your file in source directory use path as “src/student_data.json”
  3. If your project is maven project, always write script to copy file which you want to access or keep in resource folder to access because maven project create different directory structure after build.

Solution depend on your project requirement. You can use below code to get qualified full path of a file

public static void main(String [] args) {

    String filename="student_data.json";
    //To get path of file
    Path path = Paths.get(filename);
    //To print absolute path of file
    System.out.println(path.getAbsolutePath());

You would like to see

Follow below link to see more Java issues solutions

YAML and JAVA Configuration


Below are Tools which support YAML for JAVA API’s. Here I will focus only on SnakeYAML which widely used by industry.

  • JvYaml
  • SnakeYAML
  • YamlBeans
  • JYaml
  • Camel

SnakeYAML Configuration

JAVA


<dependency>
    <groupId>org.yaml</groupId>
    <artifactId>snakeyaml</artifactId>
    <version>1.20-SNAPSHOT</version>
  </dependency>

Android


<dependency>
  <groupId>org.yaml</groupId>
  <artifactId>snakeyaml</artifactId>
  <version>1.20-SNAPSHOT</version>
  <classifier>android</classifier>
</dependency>

For any operation with SnakeYAML api’s you have to use below steps:
package :

org.yaml.snakeyaml.Yaml

Intialization:
Yaml yaml = new Yaml();

Loading YAML :

  • yaml.load(String) accepts a String.
  • yaml.load(InputStream) accepts a InputStream.

yaml.load(InputStream) detects the encoding by checking the BOM (byte order mark) sequence at the beginning of streams. If no BOM presents the utf-8 encoding is assumed..

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.

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.

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.

Difference between YAML and JSON


 

“YAML is superset of JSON”

Below are comparison between YAML and JSON by conceptually and writing differences

YAML vs JSON

  • YAML is best suited for configuration while JSON is better as a serialization format or serving up data for your APIs.
  • YAML is by no means  a replacement for JSON .You should use the data format that makes the most sense for what you are trying to accomplish.

YAML Advantage

  • YAML has a couple of big advantages  including the ability to self reference, support for complex datatypes, embedded block literals, comments, and more.
  • Write your configuration files in YAML format where you have the opportunity – it is designed to be readable and easily editable by humans.

JSON Disadvantage

  • JSON designed to be human readable – intentionally lacking features to support editing.
  • JSON doesn’t support comments – this is intentionally left out of the JSON specification because its not what the format was designed for.

JSON vs YAML

  • JSON is well suited for  serialization format to data interchange between apis over network.
  • JSON ships with a far simpler specification than YAML.
  • JSON  learning is faster in comparison to YAML, because it is not nearly as robust in its feature set.
  • YAML is a superset of JSON, which means you can parse JSON with a YAML parser.

JSON Advantage

  • JSON is  best to data interchange.

Disadvantage of YAML

  • YAML parsers are younger and  known to be less secure.
  • YAML is mainly designed for configuration when use for data interchange , many of YAMLs features lose their appeal.

Syntax Difference between YAML and JSON

Below are some syntax difference in YAML and JSON while writing files:

JSON Syntax

  • JSON is a subset of the JavaScript object notation syntax.
  • JSON data stored in name/value pairs.
  • JSON records separated by commas.
  • JSON field names & strings are wrapped by double quotes.

YAML Syntax

  • YAML stands for ain’t markup language and is a superset of JSON – You Convert YAML to JSON
  • YAML files begin with ‘—‘, marking the start of the document.
  • YAML documents end with ‘…’ but it’s optional.
  • YAML key value pairs are separated by colon.
  • YAML lists begin with a hyphen.

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 exclude fields from JSON while parsing by GSON/GsonBuilder?


In below previous exaxmples. We discussed about to convert JAVA object to/ from to JSON and pretty formatting and null serailization of fields for JSON conversion. Now here we discussed about how to exclude fields/object while converting to JSON.

How to convert Java object to / from JSON by (GSON)

How to do JSON pretty formatting and Null Serialization (GSON/GsonBuilder)

GSON provide two ways to exclude fields from JSON by GsonBuilder:

  • @Expose Annotation
  • Custom Annotation

@Expose Annotation

By using the @Expose annotations and then using the excludeFieldsWithoutExposeAnnotation() method on the GsonBuilder will ignore all fields except the ones that have been exposed using the @Expose annotation.

Custom Annotation

By defining a custom annotation and ignoring fields that are annotated with exclusion class by extending ExclusionStrategy interface implementing that by using below GsonBuilder methods can ingnore/exclude fields from JSON.

Boolean shouldSkipField(FieldAttributes f);

public boolean shouldSkipClass(Class clazz);

Pre-Requisite:

  • JAVA 8
  • Maven 3
  • GSON Jar as below.

GSON Dependency:

 <dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.2</version>
 </dependency>

In below example fields middleName,educationDetail and experienceDetail will not serialize because not having @Expose annotation on it and field country will also not serialize because of having @Country annotation. Here you will see how to unsearilize all these

package gsonexamples;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import model.AlbumImages;
import model.Albums;
import model.Country;
import model.Dataset;
import model.Employee;
import util.CustomExclusionStrategy;

class GsonConvertJavaObjectToJSONExclusion {

	public static void main(String[] args) {
		Employee employee= getJavaObject();
		//CustomExclusionStrategy that will exclude the Country field.
// We also allow only those fields that have been exposed using the @Expose
//annotation

				Gson gson = new GsonBuilder()
				.setPrettyPrinting()
				.serializeNulls()
				.setExclusionStrategies(new CustomExclusionStrategy(Country.class))
				.excludeFieldsWithoutExposeAnnotation()
				.create();

		System.out.println(gson.toJson(employee));

	}

	public static  Employee getJavaObject()
	{
		Employee employee=new Employee("C123","Saurabh" ,"Kumar","Gupta","Tech Lead",50000,"Alpharetta,GA","Dallas, TX","1231231230",null,null);
		return employee;
	}

}

package util;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;

import model.Country;
import model.Dataset;

/**
 * This class use custom exclusion policy. We want to ignore all fields that
 * have been annotated with the Country annotation. Note that we can also ignore
 * fields based on name or type. This same type policy can be applied to any *  class.
 *
 */
public class CustomExclusionStrategy implements ExclusionStrategy {

	private Class classToExclude;

	public CustomExclusionStrategy(Class classToExclude) {
		this.classToExclude = classToExclude;
	}

	// This method is called for all fields. if the method returns false the
	// field is excluded from serialization
	//@Override
	public boolean shouldSkipField(FieldAttributes f) {
		if (f.getAnnotation(Country.class) == null)
			return false;

		return true;
	}

	// This method is called for all classes. If the method returns false the class is excluded.
	//@Override
	public boolean shouldSkipClass(Class<?> clazz) {
		if (clazz.equals(classToExclude))
			return true;
		return false;
	}

}
package model;

import java.util.List;
import java.util.Set;

import com.google.gson.annotations.Expose;

public class Employee {
	@Expose
	private String employeeId;
	@Expose
	private String firstName;
	private String middleName;
	@Expose
	private String lastName;
	@Expose
	private String designation;
	private int salary;
	@Expose
	private String permanentAddress;
	private String mailingAddress;
	@Country
	private String country;
	@Expose
	private String mobile;
	private Set<Education> educationDetail;
	private List<Experience> expericeDetail;

	@Override
	public String toString() {
		return "Employee [employeeId=" + employeeId + ", firstName=" + firstName + ", middleName=" + middleName
				+ ", lastName=" + lastName + ", designation=" + designation + ", salary=" + salary
				+ ", permanentAddress=" + permanentAddress + ", mailingAddress=" + mailingAddress + ", mobile=" + mobile
				+ ", educationDetail=" + educationDetail + ", expericeDetail=" + expericeDetail + "]";
	}

	public Employee(String employeeId, String firstName, String middleName, String lastName, String designation,
			int salary, String permanentAddress, String mailingAddress, String mobile, Set<Education> educationDetail,
			List<Experience> expericeDetail) {
		super();
		this.employeeId = employeeId;
		this.firstName = firstName;
		this.middleName = middleName;
		this.lastName = lastName;
		this.designation = designation;
		this.salary = salary;
		this.permanentAddress = permanentAddress;
		this.mailingAddress = mailingAddress;
		this.mobile = mobile;
		this.educationDetail = educationDetail;
		this.expericeDetail = expericeDetail;
	}
//Getter and setter of fields
	}

package model;

public class Education {
private String schoolOrCollegeName;
private String standard;
private String stream;
private double percentage;

@Override
public String toString() {
	return "Education [schoolOrCollegeName=" + schoolOrCollegeName + ", standard=" + standard + ", stream=" + stream
			+ ", percentage=" + percentage + "]";
}
public Education(String schoolOrCollegeName, String standard, String stream, double percentage) {
	super();
	this.schoolOrCollegeName = schoolOrCollegeName;
	this.standard = standard;
	this.stream = stream;
	this.percentage = percentage;
}
}
package model;

import java.util.Date;

public class Experience {
private String companyName;
private String designation;
private Date startDate;
private Date endDate;
private double salary;
public Experience(String companyName, String designation, Date startDate, Date endDate, double salary) {
	super();
	this.companyName = companyName;
	this.designation = designation;
	this.startDate = startDate;
	this.endDate = endDate;
	this.salary = salary;
}
@Override
public String toString() {
	return "Experience [companyName=" + companyName + ", designation=" + designation + ", startDate=" + startDate
			+ ", endDate=" + endDate + ", salary=" + salary + "]";
}
//getter and setter
}

Output

{
  "employeeId": "C123",
  "firstName": "Saurabh",
  "lastName": "Gupta",
  "designation": "Tech Lead",
  "permanentAddress": "Alpharetta,GA",
  "mobile": "1231231230"
}

Here in above JSON output for Employee class fields middleName, educationDetail and experienceDetail not printed because @Expose annotation was not given on that and by using CustomExlusionStartegy skiping serialization for fields country because it’s having @Country annotation as we remove in class for serialization CustomExclusionStrategy for @Country annotation.

Now in next example will discuss about.

How to parse JSON data token by token by using GSON/JsonToken/JsonReader?

How to do JSON pretty formatting and Null Serialization (GSON/GsonBuilder)


In previous example use GSON comes with simple JAVA API’s to convert JAVA object to/from JSON and here I will use GsonBuilder to print format JSON and serialize null object values also.

How to convert Java object to / from JSON by (GSON)

Pre-Requisite:

  • JAVA 8
  • Maven 3
  • GSON Jar as below.

GSON Dependency:

 <dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.2</version>
 </dependency>

Convert JAVA object to/from JSON

package gsonexamples;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import model.Employee;

public class GsonConvertJavaToJSON {

	public static void main(String[] args) {
		//Create GSON Object
		//Gson gson = new Gson();
Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
		Employee employee=getJavaObject();
		String json=gson.toJson(employee);

        System.out.println("Convert Java Object To JSON");
		System.out.println(json);

		System.out.println("Convert JSON To Java Object");
		employee=gson.fromJson(json,Employee.class);
		System.out.println(employee);

	}
	public static  Employee getJavaObject()
	{
		Employee employee=new Employee("C123","Saurabh" ,"Kumar","Gupta","Tech Lead",50000,"Alpharetta,GA","Dallas, TX","1231231230",null,null);
		return employee;
	}

}

  • GsonBuilder().setPrettyPrinting() :  This api is to generate pretty formatted JSON string.
  • GsonBuilder().searializeNulls() :  This api is to serialize null values in object.
  • GsonBuilder().create(): This api is to create GSON object to Java object to/from JSON.
package model;

import java.util.List;
import java.util.Set;

public class Employee {
private String employeeId;
private String firstName;
private String middleName;
private String lastName;
private String designation;
private int salary;
private String permanentAddress;
private String mailingAddress;
private String mobile;
private Set<Education> educationDetail;
private List<Experience> expericeDetail;

@Override
public String toString() {
	return "Employee [employeeId=" + employeeId + ", firstName=" + firstName + ", middleName=" + middleName
			+ ", lastName=" + lastName + ", designation=" + designation + ", salary=" + salary + ", permanentAddress="
			+ permanentAddress + ", mailingAddress=" + mailingAddress + ", mobile=" + mobile + ", educationDetail="
			+ educationDetail + ", expericeDetail=" + expericeDetail + "]";
}
public Employee(String employeeId, String firstName, String middleName, String lastName, String designation, int salary,
		String permanentAddress, String mailingAddress, String mobile, Set<Education> educationDetail,
		List<Experience> expericeDetail) {
	super();
	this.employeeId = employeeId;
	this.firstName = firstName;
	this.middleName = middleName;
	this.lastName = lastName;
	this.designation = designation;
	this.salary = salary;
	this.permanentAddress = permanentAddress;
	this.mailingAddress = mailingAddress;
	this.mobile = mobile;
	this.educationDetail = educationDetail;
	this.expericeDetail = expericeDetail;
}
//Getter and Setter
}

package model;

public class Education {
private String schoolOrCollegeName;
private String standard;
private String stream;
private double percentage;

@Override
public String toString() {
	return "Education [schoolOrCollegeName=" + schoolOrCollegeName + ", standard=" + standard + ", stream=" + stream
			+ ", percentage=" + percentage + "]";
}
public Education(String schoolOrCollegeName, String standard, String stream, double percentage) {
	super();
	this.schoolOrCollegeName = schoolOrCollegeName;
	this.standard = standard;
	this.stream = stream;
	this.percentage = percentage;
}
//getter and setter
}
package model;

import java.util.Date;

public class Experience {
private String companyName;
private String designation;
private Date startDate;
private Date endDate;
private double salary;
public Experience(String companyName, String designation, Date startDate, Date endDate, double salary) {
	super();
	this.companyName = companyName;
	this.designation = designation;
	this.startDate = startDate;
	this.endDate = endDate;
	this.salary = salary;
}
@Override
public String toString() {
	return "Experience [companyName=" + companyName + ", designation=" + designation + ", startDate=" + startDate
			+ ", endDate=" + endDate + ", salary=" + salary + "]";
}
//getter and setter
}

Output:

Convert Java Object To JSON
{
  "employeeId": "C123",
  "firstName": "Saurabh",
  "middleName": "Kumar",
  "lastName": "Gupta",
  "designation": "Tech Lead",
  "salary": 50000,
  "permanentAddress": "Alpharetta,GA",
  "mailingAddress": "Dallas, TX",
  "mobile": "1231231230",
  "educationDetail": null,
  "expericeDetail": null
}
<span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span>
Convert JSON To Java Object
Employee [employeeId=C123, firstName=Saurabh, middleName=Kumar, lastName=Gupta, designation=Tech Lead, salary=50000, permanentAddress=Alpharetta,GA, mailingAddress=Dallas, TX, mobile=1231231230, educationDetail=null, expericeDetail=null]

In above JSON output is pretty formatted properly and  serialize null objects for education and experience. In next blog will explain about how to exclude fields while serializing/deserializing to/from JSON by GsonBuilder.

How to exclude fields from JSON while parsing by GSON/GsonBuilder?

How to convert Java object to / from JSON by (GSON)


GSON comes with simple JAVA API’s toJson()/fromJson() to convert JAVA object to/from JSON. Below is very simple example to convert Employee Java object to JSON and Vice versa. To know more about GSON follow the link GSON Introduction.

Pre-Requisite:

  • JAVA 8
  • Maven 3
  • GSON Jar as below.

GSON Dependency:

 <dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.2</version>
 </dependency>

Convert JAVA object to/from JSON

package gsonexamples;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import model.Employee;

public class GsonConvertJavaToJSON {

	public static void main(String[] args) {
		//Create GSON Object
		Gson gson = new Gson();
		<span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span>
		Employee employee=getJavaObject();
		String json=gson.toJson(employee);

        System.out.println("Convert Java Object To JSON");
		System.out.println(json);

		System.out.println("Convert JSON To Java Object");
		employee=gson.fromJson(json,Employee.class);
		System.out.println(employee);

	}
	public static  Employee getJavaObject()
	{
		Employee employee=new Employee("C123","Saurabh" ,"Kumar","Gupta","Tech Lead",50000,"Alpharetta,GA","Dallas, TX","1231231230",null,null);
		return employee;
	}

}

package model;

import java.util.List;
import java.util.Set;

public class Employee {
private String employeeId;
private String firstName;
private String middleName;
private String lastName;
private String designation;
private int salary;
private String permanentAddress;
private String mailingAddress;
private String mobile;
private Set<Education> educationDetail;
private List<Experience> expericeDetail;

@Override
public String toString() {
	return "Employee [employeeId=" + employeeId + ", firstName=" + firstName + ", middleName=" + middleName
			+ ", lastName=" + lastName + ", designation=" + designation + ", salary=" + salary + ", permanentAddress="
			+ permanentAddress + ", mailingAddress=" + mailingAddress + ", mobile=" + mobile + ", educationDetail="
			+ educationDetail + ", expericeDetail=" + expericeDetail + "]";
}
public Employee(String employeeId, String firstName, String middleName, String lastName, String designation, int salary,
		String permanentAddress, String mailingAddress, String mobile, Set<Education> educationDetail,
		List<Experience> expericeDetail) {
	super();
	this.employeeId = employeeId;
	this.firstName = firstName;
	this.middleName = middleName;
	this.lastName = lastName;
	this.designation = designation;
	this.salary = salary;
	this.permanentAddress = permanentAddress;
	this.mailingAddress = mailingAddress;
	this.mobile = mobile;
	this.educationDetail = educationDetail;
	this.expericeDetail = expericeDetail;
}
//Getter and Setter
}

package model;

public class Education {
private String schoolOrCollegeName;
private String standard;
private String stream;
private double percentage;

@Override
public String toString() {
	return "Education [schoolOrCollegeName=" + schoolOrCollegeName + ", standard=" + standard + ", stream=" + stream
			+ ", percentage=" + percentage + "]";
}
public Education(String schoolOrCollegeName, String standard, String stream, double percentage) {
	super();
	this.schoolOrCollegeName = schoolOrCollegeName;
	this.standard = standard;
	this.stream = stream;
	this.percentage = percentage;
}
//getter and setter
}
package model;

import java.util.Date;

public class Experience {
private String companyName;
private String designation;
private Date startDate;
private Date endDate;
private double salary;
public Experience(String companyName, String designation, Date startDate, Date endDate, double salary) {
	super();
	this.companyName = companyName;
	this.designation = designation;
	this.startDate = startDate;
	this.endDate = endDate;
	this.salary = salary;
}
@Override
public String toString() {
	return "Experience [companyName=" + companyName + ", designation=" + designation + ", startDate=" + startDate
			+ ", endDate=" + endDate + ", salary=" + salary + "]";
}
//getter and setter
}

Output:

Convert Java Object To JSON

{"employeeId":"C123","firstName":"Saurabh","middleName":"Kumar","lastName":"Gupta","designation":"Tech Lead","salary":50000,"permanentAddress":"Alpharetta,GA","mailingAddress":"Dallas, TX","mobile":"1231231230"}

Convert JSON To Java Object

Employee [employeeId=C123, firstName=Saurabh, middleName=Kumar, lastName=Gupta, designation=Tech Lead, salary=50000, permanentAddress=Alpharetta,GA, mailingAddress=Dallas, TX, mobile=1231231230, educationDetail=null, expericeDetail=null]

In above JSON output is not formatted properly and not serialize null objects for education and experience. In next blog will explain about how to format JSON and serialize null values by using GsonBuilder.

How to do JSON pretty formatting and Null Serialization (GSON/GsonBuilder)

GSON Introduction


Gson is an open source Java library to serialize and de-serialize Java objects to/from JSON. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source code.

Initial Release : May 22,2008
Written in: Java
Developed By: Google
Stable Release : 2.8.2 in 19 Sep, 2017
License: Apache License 2.0

Why GSON is Popular?

  • provide simple methods toJson() and fromJson() to convert Java objects to JSON and vice-versa.
  • Extensive support of Java Generics.
  • allow custom representaion of objects.
  • allow pre-existing unmodifiable objects to be converted to and from JSON.
  • support for complex objects with generic types and having deep inheritance.

Configuration/Dependency

Below dependency required to configure GSON in your application

<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>

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.

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

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("student_data2.txt"));

		ObjectMapper objectMapper = new ObjectMapper();

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

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

		JsonNode phoneNosNode = rootNode.path("phoneNumbers");
		Iterator<JsonNode> elements = phoneNosNode.elements();
		while(elements.hasNext()){
			JsonNode phone = elements.next();
			System.out.println("Phone No = "+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 Map JSON to Java Object by Annotation?


Jackson provide annotation for mapping Java and JSON properties that help when mapping fields in JSON and Java objects are having different names and some properties are additional and not match.

Pre-Requisite 

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

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

Example

In below example showing to map Student object from JSON to Java  where field name id is in JSON while rollNumber is Java object and JAVA object also having additional field which is not mapped with any fields for this we have to use @JsonIgnoreProperties(ignoreUnknown = true) on class level to ignore this field or if some more.

Annotation Used

Ignore Unknown Properties
@JsonIgnoreProperties(ignoreUnknown = true)
JSON to Java properties match
@JsonProperty(value = "XYZ")

JSON Sample Data

Add below JSON data in student_data.txt file to execute this program.

[
{
  "id" : 11,
  "firstName" : "Saurabh",
  "lastName" : "Gupta",
  "permanent" : false,
  "address" : {
    "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"
  }
},
{
  "id" : 12,
  "firstName" : "Gaurav",
  "lastName" : "Khaira",
  "permanent" : true,
  "address" : {
    "addressLine" : " 5770 Shiloh woods dr",
    "city" : "Cumming",
    "state" : "GA",
    "zipCode" : 50007
  },
  "phoneNumbers" : [ 2233445567, 3344556678 ],
  "cities" : [ "New York", "Austin", "Plano" ],
  "properties" : {
    "play" : "Baseball",
    "interst" : "Science",
    "age" : "36 years"
  }
}
]

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("student_data.txt"));
		Student[] studentArr = null;

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

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

Model Class

Below Student and Address classes are required to execute this program. Here field rollNumber is mapping with property id and others property too and using @JsonIgnoreProperties(ignoreUnknown = true) for ignoring additional fields which are not mapped.

package test.facingissesonit.json.jacson;

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

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Student {
	@JsonProperty(value = "id")
	private int rollNumber;
	@JsonProperty(value = "firstName")
	private String firstName;
	@JsonProperty(value = "lastName")
	private String lastName;
	@JsonProperty(value = "permanent")
	private boolean permanent;
	@JsonProperty(value = "address")
	private Address address;
	@JsonProperty(value = "phoneNumbers")
	private long[] phoneNumbers;
	@JsonProperty(value = "cities")
	private List<String> cities;
	@JsonProperty(value = "properties")
	private Map<String, String> properties;
	private Date dateOfJoining =new Date();
	@Override
	public String toString()
	{
		StringBuffer sb=new StringBuffer();
		sb.append("==============Student Information================\n");
		sb.append("rollNumber=").append(rollNumber).append("\n");
		sb.append("firstName=").append(firstName).append("\n");
		sb.append("lastName=").append(lastName).append("\n");
		sb.append("permanent=").append(permanent).append("\n");
		sb.append("adress=").append(address).append("\n");
		sb.append("phoneNumbers=").append(Arrays.toString(phoneNumbers)).append("\n");
		sb.append("cities=").append(Arrays.toString(cities.toArray(new String[cities.size()]))).append("\n");
		sb.append("properties=").append(properties).append("\n");
		sb.append("dateOfJoining=").append(dateOfJoining).append("\n");
		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<String> getCities() {
		return cities;
	}
	public void setCities(List<String> cities) {
		this.cities = cities;
	}
	public Map<String, String> getProperties() {
		return properties;
	}
	public void setProperties(Map<String, String> properties) {
		this.properties = properties;
	}
	public Date getDateOfJoining() {
		return dateOfJoining;
	}
	public void setDateOfJoining(Date dateOfJoining) {
		this.dateOfJoining = dateOfJoining;
	}
}

package test.facingissesonit.json.jacson;

import com.fasterxml.jackson.annotation.JsonProperty;

public class Address {
@JsonProperty(value = "addressLine")
private String addressLine;
@JsonProperty(value = "city")
private String city;
@JsonProperty(value = "state")
private String state;
@JsonProperty(value = "zipCode")
private int zipCode;
@Override
public String toString()
{
	StringBuffer sb=new StringBuffer();
	sb.append("AddressLine=").append(addressLine).append("\n");
	sb.append("city=").append(city).append("\n");
	sb.append("state=").append(state).append("\n");
	sb.append("zipCode=").append(zipCode).append("\n");
	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

Student 1
==============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}
dateOfJoining=Sat May 20 22:41:52 EDT 2017

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

phoneNumbers=[2233445567, 3344556678]
cities=[New York, Austin, Plano]
properties={play=Baseball, interst=Science, age=36 years}
dateOfJoining=Sat May 20 22:41:52 EDT 2017

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.

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

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("student_data.txt"));
			// for pretty formatted printing
			jsonGenerator.setPrettyPrinter(new DefaultPrettyPrinter());
			// start root from here
			jsonGenerator.writeStartObject();

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

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

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

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

			jsonGenerator.writeObjectFieldStart("properties");
			Set<String> 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("Saurabh");
		student.setLastName("Gupta");
		student.setPhoneNumbers(new long[] { 2233445566L, 3344556677L });

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

		List<String> cities = new ArrayList<String>();
		cities.add("Dallas");
		cities.add("San Antonio");
		cities.add("Irving");
		student.setCities(cities);

		Map<String, String> props = new HashMap<String, String>();
		props.put("age", "34 years");
		props.put("interst", "Math");
		props.put("play", "Badminton");

		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<String> cities;
	private Map<String, String> properties;
	@Override
	public String toString()
	{
		StringBuffer sb=new StringBuffer();
		sb.append("==============Student Information================\n");
		sb.append("rollNumber=").append(rollNumber).append("\n");
		sb.append("firstName=").append(firstName).append("\n");
		sb.append("lastName=").append(lastName).append("\n");
		sb.append("permanent=").append(permanent).append("\n");
		sb.append("adress=").append(address).append("\n");
		sb.append("phoneNumbers=").append(Arrays.toString(phoneNumbers)).append("\n");
		sb.append("cities=").append(Arrays.toString(cities.toArray(new String[cities.size()]))).append("\n");
		sb.append("properties=").append(properties).append("\n");
		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<String> getCities() {
		return cities;
	}
	public void setCities(List<String> cities) {
		this.cities = cities;
	}
	public Map<String, String> getProperties() {
		return properties;
	}
	public void setProperties(Map<String, String> 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("AddressLine=").append(addressLine).append("\n");
	sb.append("city=").append(city).append("\n");
	sb.append("state=").append(state).append("\n");
	sb.append("zipCode=").append(zipCode).append("\n");
	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

{
  "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"
  }
}

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.

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

Sample Data

 Add below content in  student_data.txt

[
{
  "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"
  }
},
{
  "rollNumber" : 11,
  "firstName" : "Gaurav",
  "lastName" : "Khaira",
  "permanent" : true,
  "address" : {
    "addressLine" : " 5770 Shiloh woods dr",
    "city" : "Cumming",
    "zipCode" : 50007
  },
  "phoneNumbers" : [ 2233445567, 3344556678 ],
  "cities" : [ "New York", "Austin", "Plano" ],
  "properties" : {
    "play" : "Baseball",
    "interst" : "Science",
    "age" : "36 years"
  }
}
]

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("student_data.txt"));
		Student[] studentArr = null;

		ObjectMapper objectMapper = new ObjectMapper();
		studentArr = objectMapper.readValue(mapData, Student[].class);
		List<Student> studentList=Arrays.asList(studentArr);
		System.out.println("Student 1 \n"+studentList.get(0));
		System.out.println("Student 2 \n"+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<String> cities;
	private Map<String, String> properties;
	@Override
	public String toString()
	{
		StringBuffer sb=new StringBuffer();
		sb.append("==============Student Information================\n");
		sb.append("rollNumber=").append(rollNumber).append("\n");
		sb.append("firstName=").append(firstName).append("\n");
		sb.append("lastName=").append(lastName).append("\n");
		sb.append("permanent=").append(permanent).append("\n");
		sb.append("adress=").append(address).append("\n");
		sb.append("phoneNumbers=").append(Arrays.toString(phoneNumbers)).append("\n");
		sb.append("cities=").append(Arrays.toString(cities.toArray(new String[cities.size()]))).append("\n");
		sb.append("properties=").append(properties).append("\n");
		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<String> getCities() {
		return cities;
	}
	public void setCities(List<String> cities) {
		this.cities = cities;
	}
	public Map<String, String> getProperties() {
		return properties;
	}
	public void setProperties(Map<String, String> 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("AddressLine=").append(addressLine).append("\n");
	sb.append("city=").append(city).append("\n");
	sb.append("state=").append(state).append("\n");
	sb.append("zipCode=").append(zipCode).append("\n");
	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.

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

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("=================Convert Student Java Object to JSON==============");
		// convert Object to json string
		Student student = sampleStudentObject();

		String studentStr = convertJavaObjectToJSON(student);
		System.out.println("Student JSON Data \n" + studentStr);
		System.out.println("=================Convert JSON DATA  to Student JAVA Object==============");
		Object object = convertJSONToJavaObject(studentStr, Student.class);
		if (object != null && object instanceof Student) {
			System.out.println("Student Object\n" + (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("Saurabh");
		student.setLastName("Gupta");
		student.setPhoneNumbers(new long[] { 2233445566L, 3344556677L });

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

		List<String> cities = new ArrayList<String>();
		cities.add("Dallas");
		cities.add("San Antonio");
		cities.add("Irving");
		student.setCities(cities);

		Map<String, String> props = new HashMap<String, String>();
		props.put("age", "34 years");
		props.put("interst", "Math");
		props.put("play", "Badminton");

		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<String> cities;
	private Map<String, String> properties;
	@Override
	public String toString()
	{
		StringBuffer sb=new StringBuffer();
		sb.append("==============Student Information================\n");
		sb.append("rollNumber=").append(rollNumber).append("\n");
		sb.append("firstName=").append(firstName).append("\n");
		sb.append("lastName=").append(lastName).append("\n");
		sb.append("permanent=").append(permanent).append("\n");
		sb.append("adress=").append(address).append("\n");
		sb.append("phoneNumbers=").append(Arrays.toString(phoneNumbers)).append("\n");
		sb.append("cities=").append(Arrays.toString(cities.toArray(new String[cities.size()]))).append("\n");
		sb.append("properties=").append(properties).append("\n");
		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<String> getCities() {
		return cities;
	}
	public void setCities(List<String> cities) {
		this.cities = cities;
	}
	public Map<String, String> getProperties() {
		return properties;
	}
	public void setProperties(Map<String, String> 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("AddressLine=").append(addressLine).append("\n");
	sb.append("city=").append(city).append("\n");
	sb.append("state=").append(state).append("\n");
	sb.append("zipCode=").append(zipCode).append("\n");
	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
{
  "rollNumber" : 11,
  "firstName" : "Saurabh",
  "lastName" : "Gupta",
  "permanent" : false,
  "address" : {
    "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"
  }
}
=================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