Friday, March 14, 2014

JSON Object Simple Example Read And Write by Android

1. Write JSON to file

In below example, it write JSON data via JSONObject and JSONArray, and save it into a file named “sample.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", "cocoalibrary.com");
 obj.put("age", new Integer(50));
 
 JSONArray list = new JSONArray();
 list.add("value 1");
 list.add("value 2");
 list.add("value 3");
 
 obj.put("messages", list);
 
 try {
 
  FileWriter file = new FileWriter("c:\\sample.json");
  file.write(obj.toJSONString());
  file.flush();
  file.close();
 
 } catch (IOException e) {
  e.printStackTrace();
 }
 
 System.out.print(obj);
 
     }
 
}
Output – See content of file named “sample.json“.
{
 "age":100,
 "name":"cocoalibrary.com",
 "messages":["Name 1","Name 2","Name 3"]
}

3. Read JSON from file

Use JSONParser to read above generated JSON file “simple.json“, and display each of the values.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.cocoalibrary.JSONArray;
import org.json.cocoalibrary.JSONObject;
import org.json.cocoalibrary.parser.JSONParser;
import org.json.cocoalibrary.parser.ParseException;
 
public class JsonExample {
     public static void main(String[] args) {
 
 JSONParser parser = new JSONParser();
 
 try {
 
  Object obj = parser.parse(new FileReader("c:\\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();
 }
 
     }
 
}
Output
cocoalibrary.com
100
Name 1
Name 2
Name 3

No comments:

Post a Comment