App.java
package com.training.rs;
import java.io.FileNotFoundException;
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;
import org.json.simple.parser.ParseException;
public class App {
private static final String MY_ARRAY = "my_array";
private static final String ELEMENT2 = "element2";
private static final String ELEMENT1 = "element1";
private static final String TEST_FILE = "/tmp/json.txt";
public static void main(String[] args) throws IOException, ParseException {
App app = new App();
app.writeJSONtoFile();
app.readJSONFromFile();
}
@SuppressWarnings("unchecked")
private void writeJSONtoFile() throws IOException {
JSONObject jsonObject = new JSONObject();
jsonObject.put(ELEMENT1, "value1");
jsonObject.put(ELEMENT2, 1234);
JSONArray jsonArray = new JSONArray();
jsonArray.add("list el1");
jsonArray.add("list el2");
jsonObject.put(MY_ARRAY, jsonArray);
FileWriter file = new FileWriter(TEST_FILE);
file.write(jsonObject.toJSONString());
file.flush();
file.close();
System.out.print(jsonObject);
}
@SuppressWarnings("unchecked")
private void readJSONFromFile() throws FileNotFoundException, IOException,
ParseException {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(TEST_FILE));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get(ELEMENT1);
System.out.println(name);
long age = (Long) jsonObject.get(ELEMENT2);
System.out.println(age);
JSONArray msg = (JSONArray) jsonObject.get(MY_ARRAY);
Iterator<String> iterator = msg.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.training</groupId>
<artifactId>json_read_write</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
</dependencies>
</project>