Minggu, 28 Desember 2014

How to Read JSON String in Java - Json-Simple Example




JSON is a text format is a widely used as data-interchange language because its parsing and its generation is easy for programs. It is slowly replacing XML as most powerful data interchange format, as it is lightweight, consumes less bandwidth and also platform independent.  Though Java doesn't have built in support for parsing JSON files and objects, there are lot of good open source JSON libraries are available which can help you to read and write JSON object to file and URL. Two of the most popular JSON parsing libraries are Jackson and Gson. They are matured, rich and stable. Though there are couple of more libraries there like JSON simple, which we are going to use in this example. Between Jackson and Gson, later does very nice job in mapping JSON object and serialization. JSON is also used in request and response between client server communication. In this tutorial we are going to see how to read and write JSON to file using JSON.Simple library, and you will notice yourself how simple working with JSON is.



Since we don't have JSON support in JDK, we need to download this open source library. If you are using maven to download JAR and managing dependency, if not then you should, then you can just include following dependencies in your pom.xml file :



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




Otherwise, you have to add the newest version of json-simple-1.1.1.jar in CLASSPATH of your Java program. Also, Java 9 is coming up with built in JSON support in JDK, which will make it easier to deal with JSON format, but that will not replace existing Jackson and GSON library, which seems to be very rich with functionality.








How to create JSON File in Java



How to read and write JSON String in JAva

Here is step by step guide on how to create 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 simple Java toolkit for JSON for to encoding and decoding JSON text.  It is fully compliant with JSON specification (RFC4627) . It provides multiple functionality such as reading, writing, parsing, escape JSON text while keeping the library lightweight. It is also flexible, simple and easy to use by reusing Map and List interfaces. JSON.Simple also supports streaming output of JSON text. In this example, we have two methods for reading and writing JSON. JSONParser  parse a JSON file and return a JSON object. Once you get JSONObject, you can get individual fields by calling get() method and passing name of attribute, but you need to remember it to type cast in String or JSONArray depending upon what you are receiving. Once you receive the array, you can use Iterator to traverse through JSON array. This way you can retrieve each element of JSONArray in Java. Now, let's see how we can write JSON String to a file. Again we first need to create a JSONObject instance, then we can put data by entering key and value. If you have not noticed the similarity then let me tell you, JSONObject is just like Map while JSONArray is like List. You can see code in your write method, that we are using put() method to insert value in JSONObject and using add() method to put value inside JSONArray object. Also note, array is used to create nested structure in JSON. Once your JSON String is ready, you can write that JSON String 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.simple.JSONObject;
import org.json.simple.parser.JSONParser;

/**
* Java Program to show how to work with JSON in Java. 

 * In this tutorial, we will learn creating
* a JSON file, writing data into it and then reading from JSON file.
*
* @author Javin Paul
*/
public class JSONDemo{

public static void main(String args[]) {

// generate JSON String in 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 title = (String) json.get("title");
String author = (String) json.get("author");
long price = (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 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);

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 and Half Blood Prince","price":20,"characters":["Harry","Ron","Hermione"]}
Done
Reading JSON file from Java program
title: Harry Potter and Half Blood Prince
author: J. K. Rolling
price: 20
characters:
Harry
Ron
Hermione





That's all about how to parse JSON String in Java program. You can also use other popular library like Gson or Jackson to do the same task. I like JSON simple library to start with because it's really simple, and it provide direct mapping between Java classes and JSON variables. For example, String in Java also map 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 big thing and in coming days every Java programmer is going to write more and more code to parse or encode decode JSON String, it's better to start early and learn how to deal with JSON in Java.























Source:http://javarevisited.blogspot.com/2014/12/how-to-read-write-json-string-to-file.html

Tidak ada komentar:

Posting Komentar