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

JSON is a text format is a widely used equally data-interchange linguistic communication because its parsing as well as its generation is like shooting fish in a barrel for programs. It is like shooting fish in a barrel replacing XML equally most powerful information interchange format, equally it is lightweight, consumes less bandwidth as well as also platform independent.  Though Java doesn't accept built inward back upwards for parsing JSON files as well as objects, at that topographic point are lot of expert opened upwards origin JSON libraries are available which tin aid you lot to read as well as write JSON object to file as well as URL. Two of the most pop JSON parsing libraries are Jackson as well as Gson. They are matured, rich as well as stable. Though at that topographic point are distich of to a greater extent than libraries at that topographic point similar JSON simple, which nosotros are going to exercise inward this example. Between Jackson as well as Gson, afterward does real prissy undertaking inward mapping JSON object as well as serialization. JSON is also used inward asking as well as reply betwixt customer server communication. In this tutorial nosotros are going to encounter how to read as well as write JSON to file using JSON.Simple library, as well as you lot volition uncovering yourself how unproblematic working amongst JSON is.

Since nosotros don't accept JSON back upwards inward JDK, nosotros demand to download this opened upwards origin library. If you lot are using maven to download JAR as well as managing dependency, if non as well as thus you lot should, as well as thus you lot tin merely include next dependencies inward 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 inward CLASSPATH of your Java program. Also, Java ix is coming upwards amongst built inward JSON back upwards inward JDK, which volition acquire inward easier to bargain amongst JSON format, but that volition non supercede existing Jackson as well as GSON library, which seems to hold out real rich amongst functionality.




How to do JSON File inward Java

 JSON is a text format is a widely used equally information How to Read JSON String inward Java - Json-Simple Example
Here is mensuration past times mensuration conduct on how to do JSON file inward Java as well as how to read as well as write on that. In this tutorial nosotros are going to exercise JSON Simple opened upwards origin library, JSON.simple is a unproblematic Java toolkit for JSON for to encoding as well as decoding JSON text.  It is fully compliant amongst JSON specification (RFC4627) . It provides multiple functionality such equally reading, writing, parsing, escape JSON text patch keeping the library lightweight. It is also flexible, unproblematic as well as like shooting fish in a barrel to exercise past times reusing Map as well as List interfaces. JSON.Simple also supports streaming output of JSON text. In this example, nosotros accept ii methods for reading as well as writing JSON. JSONParser  parse a JSON file as well as render a JSON object. Once you lot acquire JSONObject, you lot tin acquire private fields past times calling get() method as well as passing refer of attribute, but you lot demand to scream upwards it to type cast inward String or JSONArray depending upon what you lot are receiving. Once you lot have the array, you lot tin exercise Iterator to traverse through JSON array. This agency you lot tin retrieve each chemical part of JSONArray inward Java. Now, let's encounter how nosotros tin write JSON String to a file. Again nosotros kickoff demand to do a JSONObject instance, as well as thus nosotros tin lay information past times entering commutation as well as value. If you lot accept non noticed the similarity as well as thus permit me tell you, JSONObject is merely similar Map patch JSONArray is similar List. You tin encounter code inward your write method, that nosotros are using put() method to insert value inward JSONObject as well as using add() method to lay value within JSONArray object. Also note, array is used to do nested construction inward JSON. Once your JSON String is ready, you lot tin write that JSON String to file past times calling toJSONString() method inward JSONObject as well as 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 present how to piece of employment amongst JSON inward Java. 
 * In this tutorial, nosotros volition acquire creating  * a JSON file, writing information into it as well as and thus reading from JSON file.  *  * @author Javin Paul  */ public class JSONDemo{      public static void main(String args[]) {          // generate JSON String inward 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 as well as 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 as well as Half Blood Prince","price":20,"characters":["Harry","Ron","Hermione"]} Done Reading JSON file from Java programme title: Harry Potter as well as Half Blood Prince author: J. K. Rolling price: 20 characters:  Harry Ron Hermione


That's all nigh how to parse JSON String inward Java program. You tin also exercise other pop library similar Gson or Jackson to do the same task. I similar JSON unproblematic library to start amongst because it's actually simple, as well as it supply immediately mapping betwixt Java classes as well as JSON variables. For example, String inward Java also map to string inward JSON, java.lang.Number maps to lay out inward JSON, as well as boolean maps to truthful as well as faux inward JSON, as well as equally I accept already said object is Map as well as array is List inward Java. All I tin tell is JSON is already a big affair as well as inward coming days every Java programmer is going to write to a greater extent than as well as to a greater extent than code to parse or encode decode JSON String, it's meliorate to start early on as well as acquire how to bargain amongst JSON inward Java.

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

Other JSON tutorials you lot may similar to explore
  • How to convert a JSON  String to POJO inward Java? (tutorial)
  • 3 Ways to parse JSON String inward Java? (tutorial)
  • How to convert JSON array to String array inward Java? (example)
  • How to convert a Map to JSON inward Java? (tutorial)
  • How to exercise Google Protocol Buffer inward Java? (tutorial)
  • How to exercise Gson to convert JSON to Java Object? (example)
  • 5 Books to Learn REST as well as RESTful Web Services (books)


P.S. - If you lot desire to acquire how to prepare RESTful Web Services using Spring Framework, depository fiscal establishment agree out Eugen Paraschiv's REST amongst Spring course. He has lately launched the certification version of the course, which is total of exercises as well as examples to farther cement the existent footing concepts you lot volition acquire from the course.

Sumber https://javarevisited.blogspot.com/

0 Response to "How To Read Json String Inward Coffee - Json-Simple Example"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel