Read a Json File in Java Jar
JSON is a text format that is widely used every bit a data-interchange language because its parsing and its generation are easy for programs. Information technology is slowly replacing XML as the most powerful data interchange format, as it is lightweight, consumes less bandwidth, and is besides platform-independent. Though Coffee doesn't accept built-in back up for parsing JSON files and objects, there are a lot of proficient open up-source JSON libraries are available which tin can assist you to read and write JSON objects to file and URL. 2 of the most pop JSON parsing libraries are Jackson and Gson. They are matured, rich, and stable.
Though there are a couple of more libraries in that location like JSON simple, which we are going to use in this instance. Between Jackson and Gson, later does a very nice chore in mapping JSON objects and serialization. JSON is also used in requests and responses between customer-server communication.
In this tutorial, we are going to meet how to read and write JSON to file using JSON.Simple library, and you volition notice how unproblematic working with JSON is.
Since we don't have JSON support in JDK, nosotros need to download this open-source library. If you lot are using maven to download JAR and managing dependency, if not then you should, then you tin can simply include the following dependencies in your pom.xml file :
<groupid>com.googlecode.json-unproblematic</groupid> < artifactid > json-uncomplicated < /artifactid > < version > 1.i < /version >
Otherwise, you have to add the newest version of json-unproblematic-1.i.1.jar in CLASSPATH of your Java program. Also, Java ix is coming up with built-in JSON back up in JDK, which will make it easier to deal with JSON format, just that will not supercede the existing Jackson and GSON library, which seems to exist very rich with functionality.
How to create JSON File in Java
Hither is a step by stride guide on how to create a JSON file in Java and how to read and write on that. In this tutorial we are going to use JSON Simple open-source library, JSON.simple is a unproblematic Java toolkit for JSON for to encoding and decoding JSON text. It is fully compliant with JSON specification (RFC4627) . It provides multiple functionalities such as reading, writing, parsing, escape JSON text while keeping the library lightweight. It is too flexible, simple, and easy to use by reusing Map and List interfaces. JSON.Simple also supports streaming output of JSON text. In this example, nosotros accept two methods for reading and writing JSON. JSONParser parse a JSON file and return a JSON object.
In one case you get JSONObject, yous can go individual fields by calling get() method and passing name of the attribute, merely you lot need to recollect it to typecast in String or JSONArray depending upon what you lot are receiving.
Once you lot receive the array, you lot can use the Iterator to traverse through JSON array. This way you can remember each element of JSONArray in Java. Now, permit'southward see how we can write JSON String to a file. Once again nosotros first demand to create a JSONObject instance, then we can put data past entering key and value. If you lot take not noticed the similarity so let me tell y'all, JSONObject is merely like Map while JSONArray is like List.
You tin can see lawmaking in your write method, that nosotros are using put() method to insert value in JSONObject and using add together() method to put the value within JSONArray object. Also note, the assortment is used to create a nested structure in JSON. Once your JSON String is ready, you lot tin write that JSON Cord to file by calling toJSONString() method in JSONObject and 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.elementary.JSONObject; import org.json.simple.parser.JSONParser; /** * Java Plan to show how to work with JSON in Coffee.
* In this tutorial, we will learn creating * a JSON file, writing information into it and and then reading from JSON file. * * @writer Javin Paul */ public class JSONDemo{ public static void master(String args[]) { // generate JSON Cord in Java writeJson("book.json"); // let'south 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 Coffee programme"); FileReader fileReader = new FileReader(file); JSONObject json = (JSONObject) parser.parse(fileReader); String title = (String) json.get("title"); Cord writer = (String) json.become("author"); long cost = (long) json.get("toll"); Organisation.out.println("title: " + title); Arrangement.out.println("author: " + writer); System.out.println("toll: " + price); JSONArray characters = (JSONArray) json.get("characters"); Iterator i = characters.iterator(); System.out.println("characters: "); while (i.hasNext()) { System.out.println(" " + i.next()); } } take hold of (Exception ex) { ex.printStackTrace(); } }
/* * Coffee Method to write JSON String to file */ public static void writeJson(String file) { JSONObject json = new JSONObject(); json.put("title", "Harry Potter and 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); endeavour { Arrangement.out.println("Writting JSON into file ..."); System.out.println(json); FileWriter jsonFileWriter = new FileWriter(file); jsonFileWriter.write(json.toJSONString()); jsonFileWriter.flush(); jsonFileWriter.close(); Organization.out.println("Washed"); } catch (IOException e) { e.printStackTrace(); } } } Output: Writting JSON into file ... {"author":"J. K. Rolling","title":"Harry Potter and One-half Blood Prince", "price":20,"characters":["Harry","Ron","Hermione"]} Done Reading JSON file from Coffee plan championship: Harry Potter and Half Claret Prince author: J. K. Rolling toll: 20 characters: Harry Ron Hermione
That's all about how to parse JSON String in Coffee programme. You can likewise use other pop libraries like Gson or Jackson to do the aforementioned chore. I like the JSON uncomplicated library to start with because it's really simple, and it provides a direct mapping between Java classes and JSON variables.
For instance, String in Java too maps to string in JSON, java.lang.Number maps to number in JSON, and boolean maps to true and false in JSON, and as I have already said object is Map and array is List in Java.
All I can say is JSON is already a large thing and in the coming days every Java developer is going to write more than and more than code to parse or encode decode JSON String, it's improve to start early on and learn how to deal with JSON in Java.
P.S. - If you lot want to larn how to develop RESTful Web Services using Spring Framework, check out Eugen Paraschiv's Rest with Spring course. He has recently launched the certification version of the course, which is full of exercises and examples to farther cement the real world concepts you will learn from the course.
Source: https://javarevisited.blogspot.com/2014/12/how-to-read-write-json-string-to-file.html
0 Response to "Read a Json File in Java Jar"
Post a Comment