Monday, January 9, 2017

Java How to read and write Json

In this post, I will show you How to read and write Json using JSON.simple.






The first, download JSON.simple maven dependency.

<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1</version>
  </dependency>
1. Write JSON to file

public class JsonSimpleExample {
     public static void main(String[] args) {

 JSONObject obj = new JSONObject();
 obj.put("name", "test");
 obj.put("age", new Integer(30));

 JSONArray list = new JSONArray();
 list.add("text1");
 list.add("text2");
 list.add("text3");

 obj.put("messages", list);

 try {

  FileWriter file = new FileWriter("E:\\sample.json");
  file.write(obj.toJSONString());
  file.flush();
  file.close();

 } catch (IOException e) {
  e.printStackTrace();
 }

 System.out.print(obj);

     }

}
Result  - See content in file sample.json

{
 "age":30,
 "name":"test",
 "messages":["text1","text2","text3"]
}
2. Read JSON file


public class JsonSimpleExample {
     public static void main(String[] args) {

 JSONParser parser = new JSONParser();

 try {

  Object obj = parser.parse(new FileReader("E:\\sample.json"));

  JSONObject jsonObject = (JSONObject) obj;

  String name = (String) jsonObject.get("name");
  System.out.println(name);

  long age = (Long) jsonObject.get("age");
  System.out.println(age);

  // loop array
  JSONArray msg = (JSONArray) jsonObject.get("messages");
  Iterator<String> iterator = msg.iterator();
  while (iterator.hasNext()) {
   System.out.println(iterator.next());
  }

 } catch (FileNotFoundException e) {
  e.printStackTrace();
 } catch (IOException e) {
  e.printStackTrace();
 } catch (ParseException e) {
  e.printStackTrace();
 }

     }

}
Results:

test
30
text1
text2
text3
Good luck!
Share:

0 comments:

Post a Comment

Total Pageviews