Tag Archives: json deserialization

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:

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. 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