How To Read Json String Inward Coffee - Json-Simple Example

Advertisement

Masukkan script iklan 970x90px

How To Read Json String Inward Coffee - Json-Simple Example

Sabtu, 27 Juni 2020

JSON is a text format is a widely used every bit data-interchange linguistic communication because its parsing together with its generation is piece of cake for programs. It is tardily replacing XML every bit most powerful information interchange format, every bit it is lightweight, consumes less bandwidth together with also platform independent.  Though Java doesn't accept built inwards back upwards for parsing JSON files together with objects, at that topographic point are lot of practiced opened upwards rootage JSON libraries are available which tin forcefulness out assist yous to read together with write JSON object to file together with URL. Two of the most pop JSON parsing libraries are Jackson together with Gson. They are matured, rich together with stable. Though at that topographic point are twain of to a greater extent than libraries at that topographic point similar JSON simple, which nosotros are going to utilization inwards this example. Between Jackson together with Gson, afterwards does real squeamish project inwards mapping JSON object together with serialization. JSON is also used inwards asking together with reply betwixt customer server communication. In this tutorial nosotros are going to encounter how to read together with write JSON to file using JSON.Simple library, together with yous volition discover yourself how uncomplicated working amongst JSON is.

Since nosotros don't accept JSON back upwards inwards JDK, nosotros demand to download this opened upwards rootage library. If yous are using maven to download JAR together with managing dependency, if non therefore yous should, therefore yous tin forcefulness out only include next dependencies inwards your pom.xml file :

    <groupid>com.googlecode.json-simple</groupid>     <artifactid> json-simple</artifactid>     <version>1.1</version>

Otherwise, yous accept to add together the newest version of json-simple-1.1.1.jar inwards CLASSPATH of your Java program. Also, Java nine is coming upwards amongst built inwards JSON back upwards inwards JDK, which volition arrive easier to bargain amongst JSON format, but that volition non supervene upon existing Jackson together with GSON library, which seems to live on real rich amongst functionality.




How to do JSON File inwards Java

 JSON is a text format is a widely used every bit information How to Read JSON String inwards Java - Json-Simple Example
Here is measuring past times measuring conduct on how to do JSON file inwards Java together with how to read together with write on that. In this tutorial nosotros are going to utilization JSON Simple opened upwards rootage library, JSON.simple is a uncomplicated Java toolkit for JSON for to encoding together with decoding JSON text.  It is fully compliant amongst JSON specification (RFC4627) . It provides multiple functionality such every bit reading, writing, parsing, escape JSON text piece keeping the library lightweight. It is also flexible, uncomplicated together with piece of cake to utilization past times reusing Map together with List interfaces. JSON.Simple also supports streaming output of JSON text. In this example, nosotros accept 2 methods for reading together with writing JSON. JSONParser  parse a JSON file together with render a JSON object. Once yous acquire JSONObject, yous tin forcefulness out acquire private fields past times calling get() method together with passing advert of attribute, but yous demand to retrieve it to type cast inwards String or JSONArray depending upon what yous are receiving. Once yous have the array, yous tin forcefulness out utilization Iterator to traverse through JSON array. This means yous tin forcefulness out retrieve each chemical factor of JSONArray inwards Java. Now, let's encounter how nosotros tin forcefulness out write JSON String to a file. Again nosotros showtime demand to do a JSONObject instance, therefore nosotros tin forcefulness out set information past times entering primal together with value. If yous accept non noticed the similarity therefore permit me tell you, JSONObject is only similar Map piece JSONArray is similar List. You tin forcefulness out encounter code inwards your write method, that nosotros are using put() method to insert value inwards JSONObject together with using add() method to set value within JSONArray object. Also note, array is used to do nested construction inwards JSON. Once your JSON String is ready, yous tin forcefulness out write that JSON String to file past times calling toJSONString() method inwards JSONObject together with using a FileWriter to write that String to file.

import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Iterator;  import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser;  /**  * Java Program to exhibit how to piece of occupation amongst JSON inwards Java. 
 * In this tutorial, nosotros volition larn creating  * a JSON file, writing information into it together with therefore reading from JSON file.  *  * @author Javin Paul  */ public class JSONDemo{      public static void main(String args[]) {          // generate JSON String inwards Java         writeJson("book.json");          // let's read         readJson("book.json");     } 
    /*      * Java Method to read JSON From File      */     public static void readJson(String file) {         JSONParser parser = new JSONParser();          try {             System.out.println("Reading JSON file from Java program");             FileReader fileReader = new FileReader(file);             JSONObject json = (JSONObject) parser.parse(fileReader);              String championship = (String) json.get("title");             String writer = (String) json.get("author");             long toll = (long) json.get("price");              System.out.println("title: " + title);             System.out.println("author: " + author);             System.out.println("price: " + price);              JSONArray characters = (JSONArray) json.get("characters");             Iterator i = characters.iterator();              System.out.println("characters: ");             while (i.hasNext()) {                 System.out.println(" " + i.next());             }          } catch (Exception ex) {             ex.printStackTrace();         }     } 
    /*      * Java Method to write JSON String to file      */     public static void writeJson(String file) {         JSONObject json = new JSONObject();         json.put("title", "Harry Potter together with Half Blood Prince");         json.put("author", "J. K. Rolling");         json.put("price", 20);          JSONArray jsonArray = new JSONArray();         jsonArray.add("Harry");         jsonArray.add("Ron");         jsonArray.add("Hermoinee");          json.put("characters", jsonArray);          try {             System.out.println("Writting JSON into file ...");             System.out.println(json);             FileWriter jsonFileWriter = new FileWriter(file);             jsonFileWriter.write(json.toJSONString());             jsonFileWriter.flush();             jsonFileWriter.close();             System.out.println("Done");          } catch (IOException e) {             e.printStackTrace();         }     }  }  Output: Writting JSON into file ... {"author":"J. K. Rolling","title":"Harry Potter together with Half Blood Prince","price":20,"characters":["Harry","Ron","Hermione"]} Done Reading JSON file from Java programme title: Harry Potter together with Half Blood Prince author: J. K. Rolling price: 20 characters:  Harry Ron Hermione


That's all most how to parse JSON String inwards Java program. You tin forcefulness out also utilization other pop library similar Gson or Jackson to do the same task. I similar JSON uncomplicated library to start amongst because it's actually simple, together with it furnish at nowadays mapping betwixt Java classes together with JSON variables. For example, String inwards Java also map to string inwards JSON, java.lang.Number maps to let on inwards JSON, together with boolean maps to truthful together with simulated inwards JSON, together with every bit I accept already said object is Map together with array is List inwards Java. All I tin forcefulness out tell is JSON is already a big affair together with inwards coming days every Java programmer is going to write to a greater extent than together with to a greater extent than code to parse or encode decode JSON String, it's improve to start early on together with larn how to bargain amongst JSON inwards Java.

Further Reading
Spring Framework 5: Beginner to Guru
Microservices amongst Spring Cloud
Master Java Web Services together with REST API amongst Spring Boot

Other JSON tutorials yous may similar to explore
  • How to convert a JSON  String to POJO inwards Java? (tutorial)
  • 3 Ways to parse JSON String inwards Java? (tutorial)
  • How to convert JSON array to String array inwards Java? (example)
  • How to convert a Map to JSON inwards Java? (tutorial)
  • How to utilization Google Protocol Buffer inwards Java? (tutorial)
  • How to utilization Gson to convert JSON to Java Object? (example)
  • 5 Books to Learn REST together with RESTful Web Services (books)


P.S. - If yous desire to larn how to prepare RESTful Web Services using Spring Framework, cheque out Eugen Paraschiv's REST amongst Spring course. He has lately launched the certification version of the course, which is total of exercises together with examples to farther cement the existent footing concepts yous volition larn from the course.