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

JSON is a text format is a widely used equally data-interchange linguistic communication because its parsing in addition to its generation is piece of cake for programs. It is slow replacing XML equally most powerful information interchange format, equally it is lightweight, consumes less bandwidth in addition to also platform independent.  Though Java doesn't accept built inwards back upwardly for parsing JSON files in addition to objects, in that place are lot of skillful opened upwardly root JSON libraries are available which tin assist you lot to read in addition to write JSON object to file in addition to URL. Two of the most pop JSON parsing libraries are Jackson in addition to Gson. They are matured, rich in addition to stable. Though in that place are span of to a greater extent than libraries in that place similar JSON simple, which nosotros are going to usage inwards this example. Between Jackson in addition to Gson, subsequently does real dainty chore inwards mapping JSON object in addition to serialization. JSON is also used inwards asking in addition to reply betwixt customer server communication. In this tutorial nosotros are going to run across how to read in addition to write JSON to file using JSON.Simple library, in addition to you lot volition reveal yourself how elementary working alongside JSON is.

Since nosotros don't accept JSON back upwardly inwards JDK, nosotros demand to download this opened upwardly root library. If you lot are using maven to download JAR in addition to managing dependency, if non in addition to thus you lot should, in addition to thus you lot tin only include next dependencies inwards your pom.xml file :

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

Otherwise, you lot accept to add together the newest version of json-simple-1.1.1.jar inwards CLASSPATH of your Java program. Also, Java ix is coming upwardly alongside built inwards JSON back upwardly inwards JDK, which volition acquire inwards easier to bargain alongside JSON format, but that volition non supervene upon existing Jackson in addition to GSON library, which seems to move real rich alongside functionality.




How to do JSON File inwards Java

 JSON is a text format is a widely used equally information How to Read JSON String inwards Java - Json-Simple Example
Here is measurement yesteryear measurement direct on how to do JSON file inwards Java in addition to how to read in addition to write on that. In this tutorial nosotros are going to usage JSON Simple opened upwardly root library, JSON.simple is a elementary Java toolkit for JSON for to encoding in addition to decoding JSON text.  It is fully compliant alongside JSON specification (RFC4627) . It provides multiple functionality such equally reading, writing, parsing, escape JSON text spell keeping the library lightweight. It is also flexible, elementary in addition to piece of cake to usage yesteryear reusing Map in addition to List interfaces. JSON.Simple also supports streaming output of JSON text. In this example, nosotros accept ii methods for reading in addition to writing JSON. JSONParser  parse a JSON file in addition to render a JSON object. Once you lot acquire JSONObject, you lot tin acquire private fields yesteryear calling get() method in addition to passing elevate of attribute, but you lot demand to yell upwardly it to type cast inwards String or JSONArray depending upon what you lot are receiving. Once you lot have the array, you lot tin usage Iterator to traverse through JSON array. This agency you lot tin retrieve each chemical share of JSONArray inwards Java. Now, let's run across how nosotros tin write JSON String to a file. Again nosotros get-go demand to do a JSONObject instance, in addition to thus nosotros tin lay information yesteryear entering primal in addition to value. If you lot accept non noticed the similarity in addition to thus permit me tell you, JSONObject is only similar Map spell JSONArray is similar List. You tin run across code inwards your write method, that nosotros are using put() method to insert value inwards JSONObject in addition to using add() method to lay value within JSONArray object. Also note, array is used to do nested construction inwards JSON. Once your JSON String is ready, you lot tin write that JSON String to file yesteryear calling toJSONString() method inwards JSONObject in addition to 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 demo how to piece of occupation alongside JSON inwards Java. 
 * In this tutorial, nosotros volition acquire creating  * a JSON file, writing information into it in addition to and thus 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 cost = (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 in addition to 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 in addition to Half Blood Prince","price":20,"characters":["Harry","Ron","Hermione"]} Done Reading JSON file from Java programme title: Harry Potter in addition to Half Blood Prince author: J. K. Rolling price: 20 characters:  Harry Ron Hermione


That's all virtually how to parse JSON String inwards Java program. You tin also usage other pop library similar Gson or Jackson to do the same task. I similar JSON elementary library to start alongside because it's actually simple, in addition to it render straight mapping betwixt Java classes in addition to JSON variables. For example, String inwards Java also map to string inwards JSON, java.lang.Number maps to lay out inwards JSON, in addition to boolean maps to truthful in addition to fake inwards JSON, in addition to equally I accept already said object is Map in addition to array is List inwards Java. All I tin tell is JSON is already a big affair in addition to inwards coming days every Java programmer is going to write to a greater extent than in addition to to a greater extent than code to parse or encode decode JSON String, it's ameliorate to start early on in addition to acquire how to bargain alongside JSON inwards Java.

Further Reading
Spring Framework 5: Beginner to Guru
Microservices alongside Spring Cloud
Master Java Web Services in addition to REST API alongside Spring Boot

Other JSON tutorials you lot 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 usage Google Protocol Buffer inwards Java? (tutorial)
  • How to usage Gson to convert JSON to Java Object? (example)
  • 5 Books to Learn REST in addition to RESTful Web Services (books)


P.S. - If you lot desire to acquire how to prepare RESTful Web Services using Spring Framework, banking corporation gibe out Eugen Paraschiv's REST alongside Spring course. He has late launched the certification version of the course, which is total of exercises in addition to examples to farther cement the existent the world concepts you lot volition acquire from the course.

Belum ada Komentar untuk "How To Read Json String Inwards Coffee - Json-Simple Example"

Posting Komentar

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel