Java - JSON

java

http://www.json.org/javadoc/org/json/JSONObject.html
http://json.org/java/
http://www.json.org/javadoc/

http://www.tutorialspoint.com/json/json_java_example.htm

// JSON

import org.json.JSONArray;
import org.json.JSONObject;

res.setContentType("application/x-json");
res.getWriter().print(json.toString());

JSONObject jsonRoot = new JSONObject();
jsonRoot.put("IDCHAPTER","");
String output = "";
output = jsonRoot.toString();
res.setContentType("application/x-json");
res.getWriter().print(output);

JSONObject obj = new JSONObject();

obj.put("name", "foo");
obj.put("num", new Integer(100));
obj.put("balance", new Double(1000.21));
obj.put("is_vip", new Boolean(true));

// Convert a Map object into a JSON object:
JSONObject j = new JSONObject(m);

// Convert a JSON object to String:
JSONObject obj = new JSONObject();
obj.put("name","foo");
obj.put("num",new Integer(100));
obj.put("balance",new Double(1000.21));
obj.put("is_vip",new Boolean(true));
StringWriter out = new StringWriter();
obj.writeJSONString(out);
String jsonText = out.toString();

// Convert a JSON string into a JSON object
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.ParseException;
import org.json.simple.parser.JSONParser;
JSONParser parser=new JSONParser();
Object obj = parser.parse(s);
JSONArray array = (JSONArray)obj;

// Write a JSON object to a file:
JSONObject obj = new JSONObject();
obj.put("name", "mkyong.com");
obj.put("age", new Integer(100));
FileWriter file = new FileWriter("c:\\test.json");
file.write(obj.toJSONString());
file.flush();
file.close();

// Reading JSON from a file:

import java.io.FileNotFoundException;
import java.io.FileReader;
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;

JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("c:\\test.json"));
JSONObject jsonObject = (JSONObject) obj;

How to basically use JSON with Java?

We need to build the json.jar file from http://www.json.org ( https://github.com/douglascrockford/JSON-java ). I've used json.jar from json.org previously, so on this page, I will be using json.org primarily.

import org.json.JSONArray;
import org.json.JSONObject;

JSONObject jsonRoot = new JSONObject();
jsonRoot.put("IDCHAPTER","");
String output = "";
output = jsonRoot.toString();
res.setContentType("application/x-json");
res.getWriter().print(output);
import org.json.simple.JSONObject;

class JsonEncodeDemo 
{
   public static void main(String[] args) 
   {
      JSONObject obj = new JSONObject();

      obj.put("name", "foo");
      obj.put("num", new Integer(100));
      obj.put("balance", new Double(1000.21));
      obj.put("is_vip", new Boolean(true));

      System.out.print(obj);
   }
}

If we have a Map or HashMap object m, how can we convert it to a JSONObject?

Simply pass it to the JSONObject constructor:

JSONObject j = new JSONObject(m);

How to convert a JSON object to string?

String jsonStr = "...";
JSONObject jsonRoot = new JSONObject(jsonStr);
JSONArray jsonArray = new JSONArray(jsonStr);
import org.json.simple.JSONObject;

class JsonEncodeDemo 
{
   public static void main(String[] args) 
   {
      JSONObject obj = new JSONObject();

      obj.put("name","foo");
      obj.put("num",new Integer(100));
      obj.put("balance",new Double(1000.21));
      obj.put("is_vip",new Boolean(true));

      StringWriter out = new StringWriter();
      obj.writeJSONString(out);

      String jsonText = out.toString();
      System.out.print(jsonText);
   }
}

How to convert a JSON string into a JSON object?

import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.ParseException;
import org.json.simple.parser.JSONParser;

class JsonDecodeDemo 
{
   public static void main(String[] args) 
   {
      JSONParser parser=new JSONParser();
      String s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
      try{
         Object obj = parser.parse(s);
         JSONArray array = (JSONArray)obj;
         System.out.println("The 2nd element of array");
         System.out.println(array.get(1));
         System.out.println();

         JSONObject obj2 = (JSONObject)array.get(1);
         System.out.println("Field \"1\"");
         System.out.println(obj2.get("1"));    

         s = "{}";
         obj = parser.parse(s);
         System.out.println(obj);

         s= "[5,]";
         obj = parser.parse(s);
         System.out.println(obj);

         s= "[5,,2]";
         obj = parser.parse(s);
         System.out.println(obj);
      }catch(ParseException pe){
         System.out.println("position: " + pe.getPosition());
         System.out.println(pe);
      }
   }
}

How to write JSON to a file?

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);

     }

}

How to JSON from a file?

import java.io.FileNotFoundException;
import java.io.FileReader;
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 JsonSimpleExample {
     public static void main(String[] args) {

    JSONParser parser = new JSONParser();

    try {

        Object obj = parser.parse(new FileReader("c:\\test.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();
    }

     }

}

If we have a JSONObject, how can we convert it to string and send it to the browser?

res.setContentType("application/x-json");
res.getWriter().print(json.toString());
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License