Wednesday, December 11, 2019

How To Parse Json To/From Coffee Object Using Jackson Example

In this representative You volition acquire how to parse a  JSON String to Java together with  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 together with 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 reply inwards amount library, Java developers are lucky to accept span of expert together with characteristic rich JSON processing libraries such every bit GSON, Jackson and JSON-simple.  Jackson inwards a high performance, ane of the fasted JSON parsing library, which besides provides streaming capability. It has no extenal dependency together with exclusively depends on JDK. It is besides powerful together with provides total binding back upward for mutual JDK classes every bit good every bit whatever Java Bean class, e.g. Player inwards our case. It besides provides information binding for Java Collection classes e.g. Map every bit good Enum.


Jackson Library

The consummate Jackson library consists of vi jounce files that are used for many diffident operation. In this representative nosotros are going to require but one, mapper-asl.jar. If you lot desire to install the total library to your projection you lot tin download together with use jackson-all-*.jar that includes all the jars. You tin download them from the Jackson Download Page.


Alternatively, If your using Maven inwards your projection (which you lot should) together with therefore you lot tin add together next dependency inwards your pom.xml.

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



You require Default Constructor inwards Your Bean Class

When I kickoff run my program, I acquire next exception because  I had parametric constructor inwards Player shape together with non bothered to add together a  no-argument default constructor :

org.codehaus.jackson.map.JsonMappingException: No suitable constructor institute 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 fault is gone. Probably this is about other argue why you lot should accept a default or no-arg constructor inwards Java class.


How to parse JSON inwards Java

Here is our sample plan to parse JSON String inwards Java. As I said, inwards this representative nosotros volition role Jackson, an opened upward root JSON parsing library alongside rich features. There are two static methods here, toJSON() which converts a Java instance to JSON together with fromJSON() method which reads a JSON file, parse it together with create Java objects. They primal object hither is ObjectMapper shape from Jackson library, which used for converting JSON to Java together with 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 together with 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 primal 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 alongside 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 together with 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 elementary Java values shape alongside getters together with setters. We volition convert Player shape instance into  * JSON String together with 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, require past times 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=" + elevate + ", sport=" + sport + ", age=" + historic catamenia + ", 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 besides create file called player.json inwards your electrical flow or projection directory.


That's all near how to parse JSON String inwards Java together with convert a Java object to JSON using Jackson API. Though in that location are span of to a greater extent than expert opened upward root library available for JSON parsing together with conversion e.g. GSON together with JSON-Simple but Jackson is ane of the best together with characteristic rich, its besides tried together with tested library inwards many places, way you lot should live picayune worried near whatever nasty põrnikas piece parsing your big JSON String.

Further Learning
Master Java Web Services together with REST API alongside Spring Boot
REST API Design, Development & Management
solution)
  • How to parse JSON Array to Java array? (solution)
  • How to convert JSON to Java Object? (example)


  • No comments:

    Post a Comment