org.json.simple使用详解

时间:2022-04-02 17:28:09

一、概览

JSON.simple是一个很简单的JSON处理,读取和写JSON数据的JAVA库,
它完全兼容JSON的标准(RFC4627).
你可以用JSON.simple来编码或解码JSON文本。


【NOTE】
如果想将对象转换成JOSN,或将JSON转换成对象,你需要考虑使用Jackson或Gson。


二、功能

JSON.simple的功能:
 . 完全兼容JSON的标准(RFC4627)
 . 提供了多个功能,如编码;
 . 使用轻量级的库来解码/解析和转换JSON文本
 . 灵活,简单并且易于被Map和List接口重用;
 . 支持流式的JSON文本输出;
 . 提供了对于JSON文本流式输入的可停止的SAX-like接口;
 . 基于解析器的头;
 . 高性能;
 . 不依赖其它的库;
 . 所有的代码和执行文件都和JDK 1.2兼容

JSON和Java 实例的映射关系:
|__JSON_______|______Java_________________|
  string                         java.lang.String
  number                      java.lang.Number
  true|false                   java.lang.Boolean
  null                           null
  array                         java.util.List
  object                        java.util.Map

在解码或解析时,JSON.simple的映射是从左边映射到右边;
在编码时,映射关系是从右边到左边;

在解码时,
默认具体的java.util.List类对应的是 org.json.simple.JSONArray; 
默认具体的java.util.Map类对应的是 org.json.simple.JSONObject; 

在编码时,
没有列在表右边的类需要实现JSONAware或JSONStreamAware(仅用于流)来实现定制化的JSON输出;
在这种情况下,JSON.simple调用JSONAware.toJSONString()或 JSONStreamAware.writeJSONString()
来确定JSON文本的结果;

三、JSON.simple 添加到Maven的pom.xml

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>

四、 JSON编码示例

4.1 编码成JSON对象 

1. Example 1-1 -编码成一个JSON对象

  //import org.json.simple.JSONObject;
  
  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));
  obj.put("nickname",null);
  System.out.print(obj);


Result: {"balance":1000.21,"num":100,"nickname":null,"is_vip":true,"name":"foo"}


JSONObject is subclass of java.util.HashMap. No ordering is provided. 
If you need strict ordering of elements use JSONValue.toJSONString( map ) 
method with ordered map implementation such as java.util.LinkedHashMap (see example 1-3).
Please refer Mapping Between JSON and Java Entities for more information.
JSONObject是Java.util.HashMap的子类,不提供排序。
如果你需要强制对元素进行排序,可以使用JSONValue.toJSONString(map)方法来实现。


2. Example 1-2 - Encode a JSON object - Streaming

  //import org.json.simple.JSONObject;
  
  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));
  obj.put("nickname",null);


  StringWriter out = new StringWriter();
  obj.writeJSONString(out);
  String jsonText = out.toString();
  System.out.print(jsonText);


Result: {"balance":1000.21,"num":100,"nickname":null,"is_vip":true,"name":"foo"}


JSONObject is subclass of java.util.HashMap. No ordering is provided. 
If you need strict ordering of elements use JSONValue.toJSONString( map ) 
method with ordered map implementation such as java.util.LinkedHashMap (see example 1-3). 
Please refer Mapping Between JSON and Java Entities for more information.


3. Example 1-3 - Encode a JSON object - Using Map

  //import java.util.LinkedHashMap;
  //import java.util.Map;
  //import org.json.simple.JSONValue;
  
  Map obj=new LinkedHashMap();
  obj.put("name","foo");
  obj.put("num",new Integer(100));
  obj.put("balance",new Double(1000.21));
  obj.put("is_vip",new Boolean(true));
  obj.put("nickname",null);
  String jsonText = JSONValue.toJSONString(obj);
  System.out.print(jsonText);


Result: {"name":"foo","num":100,"balance":1000.21,"is_vip":true,"nickname":null}


Now the order of the object entries is preserved, which is different from example 1-1. 
Please refer Mapping Between JSON and Java Entities for more information.


4. Example 1-4 - Encode a JSON object - Using Map and streaming

  //import java.util.LinkedHashMap;
  //import java.util.Map;
  //import org.json.simple.JSONValue;
  
   Map obj=new LinkedHashMap();
   obj.put("name","foo");
   obj.put("num",new Integer(100));
   obj.put("balance",new Double(1000.21));
   obj.put("is_vip",new Boolean(true));
   obj.put("nickname",null);


   StringWriter out = new StringWriter();
   JSONValue.writeJSONString(obj, out);
   String jsonText = out.toString();
   System.out.print(jsonText);


Result: {"name":"foo","num":100,"balance":1000.21,"is_vip":true,"nickname":null}


Please refer Mapping Between JSON and Java Entities for more information.


4.2 编码成JSON数组

1. Example 2-1 - Encode a JSON array

  //import org.json.simple.JSONArray;
  
  JSONArray list = new JSONArray();
  list.add("foo");
  list.add(new Integer(100));
  list.add(new Double(1000.21));
  list.add(new Boolean(true));
  list.add(null);
  System.out.print(list);


Result: ["foo",100,1000.21,true,null]


2. Example 2-2 - Encode a JSON array - Streaming

  //import org.json.simple.JSONArray;
  
  JSONArray list = new JSONArray();
  list.add("foo");
  list.add(new Integer(100));
  list.add(new Double(1000.21));
  list.add(new Boolean(true));
  list.add(null);


  StringWriter out = new StringWriter();
  list.writeJSONString(out);
  String jsonText = out.toString();
  System.out.print(jsonText);


Result: ["foo",100,1000.21,true,null]
Please refer Mapping Between JSON and Java Entities for more information.


3. Example 2-3 - Encode a JSON array - Using List

  //import org.json.simple.JSONValue;
  
  LinkedList list = new LinkedList();
  list.add("foo");
  list.add(new Integer(100));
  list.add(new Double(1000.21));
  list.add(new Boolean(true));
  list.add(null);


  String jsonText = JSONValue.toJSONString(list);
  System.out.print(jsonText);


Result: ["foo",100,1000.21,true,null]
Please refer Mapping Between JSON and Java Entities for more information.


4. Example 2-4 - Encode a JSON array - Using List and streaming

  //import org.json.simple.JSONValue;


  LinkedList list = new LinkedList();
  list.add("foo");
  list.add(new Integer(100));
  list.add(new Double(1000.21));
  list.add(new Boolean(true));
  list.add(null);


  StringWriter out = new StringWriter();
  JSONValue.writeJSONString(list, out);
  String jsonText = out.toString();
  System.out.print(jsonText);


Result: ["foo",100,1000.21,true,null]


Please refer Mapping Between JSON and Java Entities for more information.


4.3 合并两个JSON对象

Example 3 - Merge two JSON objects

  //import org.json.simple.JSONObject;
  
  JSONObject obj1 = new JSONObject();
  obj1.put("name","foo");
  obj1.put("num",new Integer(100));
  obj1.put("balance",new Double(1000.21));
                
  JSONObject obj2 = new JSONObject();
  obj2.put("is_vip",new Boolean(true));
  obj2.put("nickname",null);


  obj2.putAll(obj1);


  System.out.print(obj2);
Result: {"balance":1000.21,"num":100,"nickname":null,"is_vip":true,"name":"foo"}, 
the same as the one of Example 1.


4.4 合并两个JSON数组

Example 4 - Merge two JSON arrays

  JSONArray list1 = new JSONArray();
  list1.add("foo");
  list1.add(new Integer(100));
  list1.add(new Double(1000.21));
  
  JSONArray list2 = new JSONArray();
  list2.add(new Boolean(true));
  list2.add(null);


  list2.addAll(list1);


  System.out.print(list2);


Result: [true,null,"foo",100,1000.21], the order of which is different from the one of Example 2.


4.5 原始JSON联结

Example 5-1 - Combination of JSON primitives, JSON object and JSON arrays

  JSONArray list1 = new JSONArray();
  list1.add("foo");
  list1.add(new Integer(100));
  list1.add(new Double(1000.21));
  
  JSONArray list2 = new JSONArray();
  list2.add(new Boolean(true));
  list2.add(null);
                
  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));
  obj.put("nickname",null);
    
  obj.put("list1", list1);
  obj.put("list2", list2);
                
  System.out.println(obj);
Result: {"balance":1000.21,"list2":[true,null],"num":100,"list1":["foo",100,1000.21],"nickname":null,"is_vip":true,"name":"foo"}


Example 5-2 - Combination of JSON primitives, Map and List

  Map m1 = new LinkedHashMap();
  Map m2 = new HashMap();
  List  l1 = new LinkedList();


  m1.put("k11","v11");
  m1.put("k12","v12");
  m1.put("k13", "v13");
  m2.put("k21","v21");
  m2.put("k22","v22");
  m2.put("k23","v23");
  l1.add(m1);
  l1.add(m2);


  String jsonString = JSONValue.toJSONString(l1);
                
  System.out.println(jsonString);
Result: [{"k11":"v11","k12":"v12","k13":"v13"},{"k22":"v22","k21":"v21","k23":"v23"}]


Example 5-3 - Combination of JSON primitives, JSONObject, Map and List, and streaming

  StringWriter out = new StringWriter();
        
  JSONObject obj = new JSONObject();
  LinkedHashMap m1 = new LinkedHashMap();
  LinkedList l1 = new LinkedList();
  obj.put("k1", "v1");
  obj.put("k2", m1);
  obj.put("k3", l1);
  m1.put("mk1", "mv1");
  l1.add("lv1");
  l1.add("lv2");
  m1.put("mk2", l1);
        
  obj.writeJSONString(out);
  System.out.println("jsonString:");
  System.out.println(out.toString());
  String jsonString = obj.toJSONString();
  System.out.println(jsonString);
Result:
  jsonString:
  {"k3":["lv1","lv2"],"k1":"v1","k2":{"mk1":"mv1","mk2":["lv1","lv2"]}}
  {"k3":["lv1","lv2"],"k1":"v1","k2":{"mk1":"mv1","mk2":["lv1","lv2"]}}


4.6 定制化的JSON输出

Example 6-1 - Customize JSON outputs

/*class User implements JSONAware{
        private int id;
        private String name;
        private String password;
        
        public User(int id, String name, String password){
                this.id = id;
                this.name = name;
                this.password = password;
        }
        
        public String toJSONString(){
                StringBuffer sb = new StringBuffer();
                
                sb.append("{");
                
                sb.append(JSONObject.escape("userName"));
                sb.append(":");
                sb.append("\"" + JSONObject.escape(name) + "\"");
                
                sb.append(",");
                
                sb.append(JSONObject.escape("ID"));
                sb.append(":");
                sb.append(id);
                
                sb.append("}");
                
                return sb.toString();
        }
}*/


  JSONArray users = new JSONArray();
  users.add(new User(123,"foo1", "secret1"));
  users.add(new User(124,"foo2", "secret2"));
  users.add(new User(125,"\"foo2\"", "secret2"));
  System.out.println(users);
Result: [{userName:"foo1",ID:123},{userName:"foo2",ID:124},{userName:"\"foo2\"",ID:125}]


User.toJSONString() seems to be a bit complicated. 
The purpose is to demonstrate the usage of JSONObject.escape(). It can be simpler:
  public String toJSONString(){
    JSONObject obj = new JSONObject();
    obj.put("userName", name);
    obj.put("ID", new Integer(id));
    return obj.toString();
  }


Please refer Mapping Between JSON and Java Entities for more information. 
(Note: If you are using version 1.0.2 or earlier, you need to override Object.toString() 
of your bean to get customized output.)


Example 6-2 - Customize JSON outputs - Streaming

/*class User implements JSONStreamAware{
        private int id;
        private String name;
        private String password;
        
        public User(int id, String name, String password){
                this.id = id;
                this.name = name;
                this.password = password;
        }
        
       public void writeJSONString (Writer out) throws IOException{
                LinkedHashMap obj = new LinkedHashMap();
                obj.put("userName", name);
                obj.put("ID", new Integer(id));
                JSONValue.writeJSONString(obj, out);
       }
}*/


  JSONArray users = new JSONArray();
  users.add(new User(123,"foo1", "secret1"));
  users.add(new User(124,"foo2", "secret2"));
  users.add(new User(125,"\"foo2\"", "secret2"));
  StringWriter out = new StringWriter();
  users.writeJSONString(out);
  System.out.println(out.toString());
Result: [{"userName":"foo1","ID":123},{"userName":"foo2","ID":124},{"userName":"\"foo2\"","ID":125}]
Please note that you don't have to implement JSONStreamAware to support streaming output of your bean, 
you can only implement JSONAware instead of JSONStreamAware. 
In the latter case, JSONAware.toString() is called and the result is written to the output stream. 
You can implement JSONStreamAware for better performance. 
If a class implements both JSONStreamAware and JSONAware, JSONStreamAware is given precedence while streaming. 
Please refer Mapping Between JSON and Java Entities for more information.


五、 JSON解析示例

Example 1 - Convenient way: Use JSONValue

  System.out.println("=======decode=======");
                
  String s="[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
  Object obj=JSONValue.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=JSONValue.parse(s);
  System.out.println(obj);
                
  s="[5,]";
  obj=JSONValue.parse(s);
  System.out.println(obj);
                
  s="[5,,2]";
  obj=JSONValue.parse(s);
  System.out.println(obj);


JSONObject is a java.util.Map and JSONArray is a java.util.List,
so you can access them with standard operations of Map or List. 
Please refer Mapping Between JSON and Java Entities for more information on entity mapping while parsing.


Example 2 - Faster way: Reuse instance of JSONParser

  JSONParser parser=new JSONParser();


  System.out.println("=======decode=======");
                
  String s="[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
  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);


JSONObject is a java.util.Map and JSONArray is a java.util.List, 
so you can access them with standard operations of Map or List. 
Please refer Mapping Between JSON and Java Entities for more information on entity mapping while parsing.


Example 3 - Exception handling

  String jsonText = "[[null, 123.45, \"a\\tb c\"]}, true";
  JSONParser parser = new JSONParser();
                
  try{
    parser.parse(jsonText);
  }
  catch(ParseException pe){
    System.out.println("position: " + pe.getPosition());
    System.out.println(pe);
  }
Result:


  position: 25
  Unexpected token RIGHT BRACE(}) at position 25.
Please refer ParseException.java for more information.


Example 4 - Container factory

You can use ContainerFactory to create containers for parsed JSON objects and JSON arrays:


  String jsonText = "{\"first\": 123, \"second\": [4, 5, 6], \"third\": 789}";
  JSONParser parser = new JSONParser();
  ContainerFactory containerFactory = new ContainerFactory(){
    public List creatArrayContainer() {
      return new LinkedList();
    }


    public Map createObjectContainer() {
      return new LinkedHashMap();
    }
                        
  };
                
  try{
    Map json = (Map)parser.parse(jsonText, containerFactory);
    Iterator iter = json.entrySet().iterator();
    System.out.println("==iterate result==");


    while(iter.hasNext()){
      Map.Entry entry = (Map.Entry)iter.next();
      System.out.println(entry.getKey() + "=>" + entry.getValue());
    }
                        
    System.out.println("==toJSONString()==");
    System.out.println(JSONValue.toJSONString(json));
  }
  catch(ParseException pe){
    System.out.println(pe);
  }
Result:


  ==iterate result==
  first=>123
  second=>[4, 5, 6]
  third=>789
  ==toJSONString()==
  {"first":123,"second":[4,5,6],"third":789}


If you don't specify a container factory, 
org.json.simple.JSONObject is used for a Map and org.json.simple.JSONArray is used for a List. 
Please refer Mapping Between JSON and Java Entities for more information on entity mapping while parsing.


Example 5 - Stoppable SAX-like content handler
JSON.simple introduces a simplified and stoppable SAX-like content handler to process JSON text stream.
The user can pause at any point of the logical input stream, processing other logic, 
then resume parsing if needed, or abort parsing if he gets the desired result, 
without having to wait for the whole input stream to finish. 
Then we have a very fast parser without sacrificing the flexibility. 
Here's an example of finding values of any object entry that matches a desired key:


KeyFinder.java:


class KeyFinder implements ContentHandler{
  private Object value;
  private boolean found = false;
  private boolean end = false;
  private String key;
  private String matchKey;
        
  public void setMatchKey(String matchKey){
    this.matchKey = matchKey;
  }
        
  public Object getValue(){
    return value;
  }
        
  public boolean isEnd(){
    return end;
  }
        
  public void setFound(boolean found){
    this.found = found;
  }
        
  public boolean isFound(){
    return found;
  }
        
  public void startJSON() throws ParseException, IOException {
    found = false;
    end = false;
  }


  public void endJSON() throws ParseException, IOException {
    end = true;
  }


  public boolean primitive(Object value) throws ParseException, IOException {
    if(key != null){
      if(key.equals(matchKey)){
        found = true;
        this.value = value;
        key = null;
        return false;
      }
    }
    return true;
  }


  public boolean startArray() throws ParseException, IOException {
    return true;
  }


        
  public boolean startObject() throws ParseException, IOException {
    return true;
  }


  public boolean startObjectEntry(String key) throws ParseException, IOException {
    this.key = key;
    return true;
  }
        
  public boolean endArray() throws ParseException, IOException {
    return false;
  }


  public boolean endObject() throws ParseException, IOException {
    return true;
  }


  public boolean endObjectEntry() throws ParseException, IOException {
    return true;
  }
}


Main logic:


  String jsonText = "{\"first\": 123, \"second\": [{\"k1\":{\"id\":\"id1\"}}, 4, 5, 6, {\"id\": 123}], \"third\": 789, \"id\": null}";
  JSONParser parser = new JSONParser();
  KeyFinder finder = new KeyFinder();
  finder.setMatchKey("id");
  try{
    while(!finder.isEnd()){
      parser.parse(jsonText, finder, true);
      if(finder.isFound()){
        finder.setFound(false);
        System.out.println("found id:");
        System.out.println(finder.getValue());
      }
    }           
  }
  catch(ParseException pe){
    pe.printStackTrace();
  }
Result:


  found id:
  id1
  found id:
  123
  found id:
  null
Please refer ContentHandler.java for more information.


Example 6 - Build whole object graph on top of SAX-like content handler
Please note that JSON.simple has provided the build in functionality to do the same work.
 Please refer above examples for more information. 
Here is just an example to show how to use the SAX-like interface in a slightly more complex scenario.


Transformer.java:


class Transformer implements ContentHandler{
        private Stack valueStack;
        
        public Object getResult(){
            if(valueStack == null || valueStack.size() == 0)
                return null;
            return valueStack.peek();
        }
        
        public boolean endArray () throws ParseException, IOException {
            trackBack();
            return true;
        }


        public void endJSON () throws ParseException, IOException {}


        public boolean endObject () throws ParseException, IOException {
            trackBack();
            return true;
        }


        public boolean endObjectEntry () throws ParseException, IOException {
            Object value = valueStack.pop();
            Object key = valueStack.pop();
            Map parent = (Map)valueStack.peek();
            parent.put(key, value);
            return true;
        }


        private void trackBack(){
            if(valueStack.size() > 1){
                Object value = valueStack.pop();
                Object prev = valueStack.peek();
                if(prev instanceof String){
                    valueStack.push(value);
                }
            }
        }
        
        private void consumeValue(Object value){
            if(valueStack.size() == 0)
                valueStack.push(value);
            else{
                Object prev = valueStack.peek();
                if(prev instanceof List){
                    List array = (List)prev;
                    array.add(value);
                }
                else{
                    valueStack.push(value);
                }
            }
        }
        
        public boolean primitive (Object value) throws ParseException, IOException {
            consumeValue(value);
            return true;
        }


        public boolean startArray () throws ParseException, IOException {
            List array = new JSONArray();
            consumeValue(array);
            valueStack.push(array);
            return true;
        }


        public void startJSON () throws ParseException, IOException {
            valueStack = new Stack();
        }


        public boolean startObject () throws ParseException, IOException {
            Map object = new JSONObject();
            consumeValue(object);
            valueStack.push(object);
            return true;
        }


        public boolean startObjectEntry (String key) throws ParseException, IOException {
            valueStack.push(key);
            return true;
        }
        
    }
Main logic:


    String jsonString = <Input JSON text>;
    Object value = null;
    JSONParser parser = new JSONParser();
    Transformer transformer = new Transformer();
        
    parser.parse(jsonString, transformer);
    value = transformer.getResult();
The result is similar to one return from the following code:


    String jsonString = <Input JSON text>;
    Object value = null;
    JSONParser parser = new JSONParser();
    value = parser.parse(jsonString);


Notes - Multithreading and extensions


JSONParser is NOT thread-safe. And please note that JSON string such as [5,,,2] 
is accepted by the parser and is treated as [5,2]. This doesn't violate the JSON specification, 
and it increases the error toleration of the input data. Some JSON grammar checker may need a 'strict' mode. 
Considering adding this feature.


Since it's a bit controversial on the extension of the parser (see comments of this wiki page), 
I'd like to make some clarifications on this topic here.


Some users may concern about exchanging important data, say medical information or financial data, 
between applications. I think you need to make sure the following things in such scenarios:


You need to make sure you are using a reliable and full compliant encoder on the side of the source;
Or if you also accept data from a non-trusted source, even a 'strict' decoder is inadequate. 
You may need extra validation rules to verify the source.
For example, a user may send totally compliant [5,2] even though you expect [5,0,2].
In both cases, a liberal parser will do nothing harmful to your application.


The reason of accepting something like [5,,2] is that:


A careless user or an encoder may repeat a comma (such as by pressing the key too long :-), which is harmless;
The comma is actually redundant syntactically, if two adjacent entities are recognized.
I know some users may be FUD in front of a liberal parser, 
but as I mentioned above, it's harmless and is allowed in RFC4627 
(actually the author of RFC4627 adopts this feature in the reference implementation).


Please feel free to leave a comment or post in the discussion group if you have further concerns. Thanks.




六、 Escaping text that contains special characters

JSONObject.escape() escapes quotes,\, /, \r, \n, \b, \f, \t and other control characters. 
It can be used to escape JavaScript codes.


  String s = "\"foo\" is not \"bar\". specials: \b\r\n\f\t\\/";


  s = JSONObject.escape(s);
                
  System.out.println(s);
Result:


  \"foo\" is not \"bar\". specials: \b\r\n\f\t\\\/




七、从文件读写JSON示例

1. 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":"mkyong.com",
"messages":["msg 1","msg 2","msg 3"]
}


2. Read JSON from file

Use JSONParser to read above generated JSON file “test.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.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();
}


     }


}


Output:


mkyong.com
100
msg 1
msg 2
msg 3