How to Parse JSON to/from Java Object using Jackson Example

In this illustration You volition larn how to parse a  JSON String to Java as well as  how to convert Java Object to JSON format using Jackson. JSON stands for JavaScript Object annotation is a subset of JavaScript object syntax, which allows all JavaScript customer to procedure it without using whatever external library. Because of its compact size, compared to XML as well as platform independence nature makes JSON a favorite format for transferring information via HTTP. Though Java doesn't accept whatever inbuilt back upward to parse JSON answer inward essence library, Java developers are lucky to accept twosome of expert as well as characteristic rich JSON processing libraries such every bit GSON, Jackson and JSON-simple.  Jackson inward a high performance, 1 of the fasted JSON parsing library, which too provides streaming capability. It has no extenal dependency as well as exclusively depends on JDK. It is too powerful as well as provides total binding back upward for mutual JDK classes every bit good every bit whatever Java Bean class, e.g. Player inward our case. It too provides information binding for Java Collection classes e.g. Map every bit good Enum.


Jackson Library

The consummate Jackson library consists of half dozen jolt files that are used for many diffident operation. In this illustration nosotros are going to postulate but one, mapper-asl.jar. If you lot desire to install the total library to your projection you lot tin download as well as use jackson-all-*.jar that includes all the jars. You tin download them from the Jackson Download Page.


Alternatively, If your using Maven inward your projection (which you lot should) as well as then you lot tin add together next dependency inward your pom.xml.

<dependency>       <groupId>org.codehaus.jackson</groupId>       <artifactId>jackson-all</artifactId>       <version>1.9.11</version> </dependency>


You postulate Default Constructor inward Your Bean Class

When I showtime run my program, I acquire next exception because  I had parametric constructor inward Player shape as well as non bothered to add together a  no-argument default constructor :

org.codehaus.jackson.map.JsonMappingException: No suitable constructor flora for type [simple type, class Player]: tin not instantiate from JSON object (need to add/enable type information?) at [Source: player.json; line: 1, column: 2]                at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163)                at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObjectUsingNonDefault(BeanDeserializer.java:746)                at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:683)                at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:580)                at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2732)                at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1817)                at JSONParser.toJava(Testing.java:30)                at JSONParser.main(Testing.java:17)

Once I added the default constructor on Player shape this mistake is gone. Probably this is around other argue why you lot should accept a default or no-arg constructor inward Java class.


How to parse JSON inward Java

Here is our sample computer program to parse JSON String inward Java. As I said, inward this illustration nosotros volition piece of occupation Jackson, an opened upward rootage JSON parsing library amongst rich features. There are two static methods here, toJSON() which converts a Java instance to JSON as well as fromJSON() method which reads a JSON file, parse it as well as create Java objects. They fundamental object hither is ObjectMapper shape from Jackson library, which used for converting JSON to Java as well as vice-versa.

import java.io.File; import java.io.IOException; import java.util.Arrays;  import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper;  /**  * Java Program to parse JSON String to Java object as well as converting a Java object to equivalent  * JSON String.  *  * @author Javin Paul  */ public class JSONParser {      public static void main(String args[]) {         toJSON();  // converting Java object to JSON String         toJava();  // parsing JSON file to create Java object     }      /**      * Method to parse JSON String into Java Object using Jackson Parser.      *      */     public static void toJava() {                 // this is the fundamental object to convert JSON to Java         ObjectMapper mapper = new ObjectMapper();          try {             File json = new File("player.json");             Player cricketer = mapper.readValue(json, Player.class);             System.out.println("Java object created from JSON String :");             System.out.println(cricketer);          } catch (JsonGenerationException ex) {             ex.printStackTrace();         } catch (JsonMappingException ex) {             ex.printStackTrace();         } catch (IOException ex) {             ex.printStackTrace();          }     }      /**      * Java method to convert Java Object into JSON String amongst assist of Jackson API.      *      */     public static void toJSON() {         Player kevin = new Player("Kevin", "Cricket", 32, 221, new int[]{33, 66, 78, 21, 9, 200});          // our span from Java to JSON as well as vice versa         ObjectMapper mapper = new ObjectMapper();          try {             File json = new File("player.json");             mapper.writeValue(json, kevin);             System.out.println("Java object converted to JSON String, written to file");             System.out.println(mapper.writeValueAsString(kevin));          } catch (JsonGenerationException ex) {             ex.printStackTrace();         } catch (JsonMappingException ex) {             ex.printStackTrace();         } catch (IOException ex) {             ex.printStackTrace();          }     }  }  /*  * Influenza A virus subtype H5N1 uncomplicated Java values shape amongst getters as well as setters. We volition convert Player shape instance into  * JSON String as well as a JSON object to Player instance.  */ class Player {      private String name;     private String sport;     private int age;     private int id;     private int[] lastScores;      public Player() {         //just there, postulate yesteryear Jackson library     }      public Player(String name, String sport, int age, int id, int[] lastinnings) {         this.name = name;         this.sport = sport;         this.age = age;         this.id = id;         lastScores = lastinnings;     }      public final String getName() {         return name;     }      public final String getSport() {         return sport;     }      public final int getAge() {         return age;     }      public final int getId() {         return id;     }      public final int[] getLastScores() {         return lastScores;     }      public final void setName(String name) {         this.name = name;     }      public final void setSport(String sport) {         this.sport = sport;     }      public final void setAge(int age) {         this.age = age;     }      public final void setId(int id) {         this.id = id;     }      public final void setLastScores(int[] lastScores) {         this.lastScores = lastScores;     }      @Override     public String toString() {         return "Player [name=" + nurture + ", sport=" + sport + ", age=" + historic menses + ", id=" + id                 + ", recent scores=" + Arrays.toString(lastScores) + "]";     }  }   Output: Java object converted to JSON String, written to file {"name":"Kevin","sport":"Cricket","age":32,"id":221,"lastScores":[33,66,78,21,9,200]} Java object created from JSON String : Player [name=Kevin, sport=Cricket, age=32, id=221, recent scores=[33, 66, 78, 21, 9, 200]]


This volition too create file called player.json inward your electrical current or projection directory.


That's all nigh how to parse JSON String inward Java as well as convert a Java object to JSON using Jackson API. Though at that topographic point are twosome of to a greater extent than expert opened upward rootage library available for JSON parsing as well as conversion e.g. GSON as well as JSON-Simple but Jackson is 1 of the best as well as characteristic rich, its too tried as well as tested library inward many places, way you lot should live piddling worried nigh whatever nasty põrnikas spell parsing your big JSON String.

If you lot similar this tutorial as well as desire to know to a greater extent than nigh how to piece of occupation amongst JSON as well as Java, cheque out next fantastic articles :
  • How to read JSON String from File inward Java (solution)
  • How to parse JSON Array to Java array? (solution)
  • How to convert JSON to Java Object? (example)


Subscribe to receive free email updates:

0 Response to "How to Parse JSON to/from Java Object using Jackson Example"

Posting Komentar