JSON.simple example – Write JSON

1. JSON.simple Dependency

JSON.simple is available at Maven central repository, just declares following dependency in your pom.xml file.

<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1</version>
</dependency>

2. Write JSON to file

In below example, it write JSON data via JSONObject and JSONArray, and save it into a file named “test.json“.

import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

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

JSONObject obj = new JSONObject();
obj.put(“name”, “mkyong.com”);
obj.put(“age”, new Integer(100));

JSONArray list = new JSONArray();
list.add(“msg 1”);
list.add(“msg 2”);
list.add(“msg 3”);

obj.put(“messages”, list);

try {

FileWriter file = new FileWriter(“c:\\test.json”);
file.write(obj.toJSONString());
file.flush();
file.close();

} catch (IOException e) {
e.printStackTrace();
}
System.out.print(obj);
}
}

Output – See content of file named “test.json“.

{
“age”:100,
“name”:”seleniumsuite.com”,
“messages”:[“msg 1″,”msg 2″,”msg 3”]
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s