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 together with its generation is like shooting fish in a barrel for programs. It is slow replacing XML equally most powerful information interchange format, equally it is lightweight, consumes less bandwidth together with also platform independent. Though Java doesn't bring built inward back upward for parsing JSON files together with objects, at that spot are lot of adept opened upward root JSON libraries are available which tin assist you lot 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 spot are dyad of to a greater extent than libraries at that spot similar JSON simple, which nosotros are going to utilisation inward this example. Between Jackson together with Gson, afterward does real prissy project inward mapping JSON object together with serialization. JSON is also used inward asking together with reply betwixt customer server communication. In this tutorial nosotros are going to run across how to read together with write JSON to file using JSON.Simple library, together with you lot volition uncovering yourself how uncomplicated working alongside JSON is.
Since nosotros don't bring JSON back upward inward JDK, nosotros demand to download this opened upward root library. If you lot are using maven to download JAR together with managing dependency, if non together with thence you lot should, together with thence you lot tin only include next dependencies inward your pom.xml file :
Since nosotros don't bring JSON back upward inward JDK, nosotros demand to download this opened upward root library. If you lot are using maven to download JAR together with managing dependency, if non together with thence you lot should, together with thence you lot tin only 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 bring to add together the newest version of json-simple-1.1.1.jar inward CLASSPATH of your Java program. Also, Java ix is coming upward alongside built inward JSON back upward inward JDK, which volition acquire inward easier to bargain alongside JSON format, but that volition non supervene upon existing Jackson together with GSON library, which seems to endure real rich alongside functionality.
How to do JSON File inward Java
Here is measurement yesteryear measurement conduct on how to do JSON file inward Java together with how to read together with write on that. In this tutorial nosotros are going to utilisation JSON Simple opened upward root library, JSON.simple is a uncomplicated Java toolkit for JSON for to encoding together with decoding JSON text. It is fully compliant alongside JSON specification (RFC4627) . It provides multiple functionality such equally reading, writing, parsing, escape JSON text piece keeping the library lightweight. It is also flexible, uncomplicated together with like shooting fish in a barrel to utilisation yesteryear reusing Map together with List interfaces. JSON.Simple also supports streaming output of JSON text. In this example, nosotros bring 2 methods for reading together with writing JSON. JSONParser parse a JSON file together with render a JSON object. Once you lot acquire JSONObject, you lot tin acquire private fields yesteryear calling get() method together with passing advert of attribute, but you lot demand to yell back it to type cast inward String or JSONArray depending upon what you lot are receiving. Once you lot have the array, you lot tin utilisation Iterator to traverse through JSON array. This agency you lot tin retrieve each chemical factor of JSONArray inward Java. Now, let's run across how nosotros tin write JSON String to a file. Again nosotros start demand to do a JSONObject instance, together with thence nosotros tin pose information yesteryear entering primal together with value. If you lot bring non noticed the similarity together with thence permit me tell you, JSONObject is only similar Map piece JSONArray is similar List. You tin run across code inward your write method, that nosotros are using put() method to insert value inward JSONObject together with using add() method to pose 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 yesteryear calling toJSONString() method inward 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 present how to piece of job alongside JSON inward Java.
* In this tutorial, nosotros volition larn creating * a JSON file, writing information into it together with and thence 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 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 nigh how to parse JSON String inward Java program. You tin also utilisation other pop library similar Gson or Jackson to do the same task. I similar JSON uncomplicated library to start alongside because it's actually simple, together with it render forthwith mapping betwixt Java classes together with JSON variables. For example, String inward Java also map to string inward JSON, java.lang.Number maps to pose out inward JSON, together with boolean maps to truthful together with faux inward JSON, together with equally I bring already said object is Map together with array is List inward Java. All I tin nation is JSON is already a big affair together with inward 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 alongside JSON inward Java.
Further Reading
Spring Framework 5: Beginner to Guru
Microservices alongside Spring Cloud
Master Java Web Services together with REST API alongside 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 utilisation Google Protocol Buffer inward Java? (tutorial)
- How to utilisation Gson to convert JSON to Java Object? (example)
- 5 Books to Learn REST together with RESTful Web Services (books)
P.S. - If you lot desire to larn how to railroad train RESTful Web Services using Spring Framework, banking concern lucifer out Eugen Paraschiv's REST alongside Spring course. He has of late launched the certification version of the course, which is total of exercises together with examples to farther cement the existent globe concepts you lot volition larn from the course.

Komentar
Posting Komentar