org.json.simple使用详解

掌握Java JSON处理:必备jar包详解 JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。它基于JavaScript的一个子集。数据在键值对中存储,就像JavaScript中的对象,或者Python中的字典,或者Java中的Map。JSON格式经常被用于Web应用中的前后端数据交换。在Java中,处理JSON数据经常涉及到将JSON字符串解析为Java对象,或者将Java对象序列化成JSON字符串。 阅读详情
AI摘要

本文介绍了JSON.simple库的基本功能及使用方法,包括JSON数据的编码、解码、合并及定制化输出等,并通过示例展示了如何在Java中操作JSON数据。

一、概览

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

Java数据转换至JSON的综合解决方案包 本文还有配套的精品资源,点击获取 简介:在Java开发中,JSON格式数据转换是处理Web服务和API接口时的基础需求。本压缩包包含了多个Java到JSON转换的主流库,包括Jackson、Gson、Json-P、Json-B、org.json和JSON.simple等,每个库都有其特点和使用场景。这些库能够实现Java对象与JSON字符串之间的相互转换,支持处理JSON数... 阅读详情

相关推荐

Waymo数据集里的隐藏彩蛋:5个激光雷达数据融合实战(附Python代码)

本文深入解析Waymo数据集中5个激光雷达的数据融合技术,提供Python实战代码,帮助开发者掌握多传感器协同工作的关键方法。通过时间同步、坐标转换和运动补偿等技术,实现高精度3D场景重建,提升自动驾驶系统的环境感知能力。

weixin_30399821的博客 82

【第三方JSON库】org.json.simple用法初探—Java编程【Eclipse平台】【不使用项目管理工具】【不添加依赖解析】

JSON.simple是一种由纯java开发的开源JSON库,包含在JSON.simple.jar中。因此需要下载一个JSON.simple.jar的JAR文件包,并在【Eclipse平台】配置构建路径。默认具体的java.util.List类对应的是 org.json.simple.JSONArray;默认具体的java.util.Map类对应的是 org.json.simple.JSONObject;

weixin_42369079的博客 2430

电源设计之路-Buck电源环路设计(Type IIIA&Type IIIB)

在对Buck 环路补偿Type II拓扑进行仿真测试后,对瞬态波形以及伯德图已经有感官上的认知;然后再进一步对Type IIIA & IIIB进一步的学习;进一步了解Cout电容量和ESR对环路补偿的影响;认识到一个电源,不是参考Datasheet上的参数进行选值就行;更需要根据实际情况,功率电感值、输出电容值以及不同电容会有不一样的ESR,这些都会对环路参数产生一定的影响

2503_92839756的博客 753

org.json.simple(JSONObject,JSONArray,JSONOValue)使用超详解

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

benm_____的博客 2623

OpenWRT端口转发与NAT环回冲突的排查与解决

本文详细解析了OpenWRT路由器中端口转发与NAT环回功能冲突导致的内网访问故障。通过生活化类比阐明两者工作原理,提供从基础诊断到内核参数调整、LuCI选项配置及手动编写iptables规则的多套解决方案,并给出进阶排查思路,帮助用户彻底解决内网无法通过公网地址访问服务的常见问题。

weixin_29243279的博客 507

雨流计数法的matlab实现,采用三点法与四点法

介绍雨流计数法是20世纪50年代由英国的两位工程师M.Matsuishi和T.Endo提出来的。该计数法的主要功能是把实测载荷历程简化为若干个载荷循环,供疲劳寿命估算和编制疲劳试验载荷谱使用。它以双参数法为基础,考虑了动强度(幅值)和静强度(均值)两个变量,符合疲劳载荷本身固有的特性。雨流计数法主要用于工程界,特别在疲劳寿命计算中运用非常广泛计数规则(1)雨流依次从载荷时间历程的峰值位置的内侧沿着...

u011391128的博客 3万+

推荐开源项目:Json-Simple - 简单易用的JSON库

Json-Simple是一个轻量级的Java库,专为处理JSON(JavaScript Object Notation)数据格式而设计。其主要目标是提供一个简单、直观的API,使得开发者可以轻松地序列化和反序列化Java对象到JSON,反之亦然。该项目托管在[Google Code](http://code.google.com/p/json-simple/)上,具有广泛的社区支持和持续的更新维护

gitblog_00068的博客 655

STM32H743IIT6上LVGL移植实战:从零到触摸屏驱动的完整配置流程

本文详细记录了在STM32H743IIT6高性能MCU上,从零开始移植LVGL图形库到7寸RGB触摸屏的完整实战流程。内容涵盖工程搭建、显示与触摸驱动配置、LVGL核心优化及常见问题排查,重点讲解了如何利用STM32H743的硬件特性(如DMA2D、LTDC)提升GUI性能,为嵌入式GUI开发提供了一份详实的配置指南。

spark7igniter的博客 549

json-simple简明教程

JSON.simple example – Read and write JSON JSON.simple, is a simple Java library for JSON processing, read and write JSON data  and full compliance with JSON specification (RFC4627). Note To co

北雨南萍 5112

开源TMS系统cortex-tms私有化部署与二次开发实战指南

运输管理系统(TMS)是现代物流数字化的核心组件,它通过将线下零散的物流操作转化为线上标准化、可追溯的数据流,实现订单、调度、跟踪与结算的全流程管理。其技术原理通常基于微服务架构,采用Spring Boot、Vue.js等成熟技术栈构建,确保系统的稳定性和可扩展性。TMS的技术价值在于显著提升物流企业的运营效率、降低成本并增强过程可控性,尤其适用于中小型物流企业实现从手工管理到系统化管理的跨越。在应用场景上,TMS广泛应用于车队管理、订单跟踪和财务结算等环节。本文聚焦于开源TMS项目cortex-tms,深

weixin_42523907的博客 746

BQ25798双电源输入4节电池升降压充电与最大功率跟踪于光伏板应用

介绍一颗具有窄范围直流电压NVDC、路径管理PPMT、光伏板最大功率跟踪及反向放电OTG升降压充电控制器,带I2C接口能对内部寄存器做控制

linkedin_38804946的博客 1678

javac错误: 程序包org.json.simple.parser不存在

来分隔这些jar包(当然写起来很冗余,目前还没找到别的方式实现)手动添加app文件夹下java代码所需要的多个jar包,用。

weixin_45207024的博客 886

SAP 打印输出中 `#` 字符替代日文汉字的根本原因与全面解决方案

只要认清设备类型 / 字符集 / 字体三角关系,并合理利用PDFUCSWINCF或 UPE + URDT,LP01里那些恼人的就会彻底消失,日文汉字将在纸面与 PDF 中如预览一样完美呈现。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 816

项目中Java Resources有红叉, 以及org.json.simple报错问题

项目中Java Resources有红叉 https://blog.csdn.net/qq_38334410/article/details/78820227 org.json.simple报错问题 pom.xml加入依赖 <dependency> <groupId>com.googlecode.json-simple</groupId> ...

weixin_42475367的博客 1092

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

org.json.simple 使用详解

一、概览 JSON.simple是一个很简单的JSON处理,读取和写JSON数据的JAVA库, 它完全兼容JSON的标准(RFC4627). 你可以用JSON.simple来编码或解码JSON文本。 【NOTE】 如果想将对象转换成JOSN,或将JSON转换成对象,你需要考虑使用Jackson或Gson。 二、功能 JSON.simple的功能: . 完全兼容JSON的标准(RFC4627) . ...

zcaixx的博客 631

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

org.json.simple.JSONObject 解析 json 替代 Alibaba FastJson

示例代码如下: import org.json.simple.JSONObject; JSONObject json = (JSONObject)JSONValue.parse(reader); return (String)json.get("id");

tonglingtou1875的博客 1017

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

org.json和json_simple-1.1性能测试

<br />org.json和json_simple-1.1性能测试 <br />测试方法:<br />//org.json<br />protected void doGet(HttpServletRequest request,<br />            HttpServletResponse response) throws ServletException, IOException {<br />        // TODO Auto-generated method stub<br />

zerolwp的专栏 1733

org.json.simple JSONArray JSONObject

public static void main(String[] args) { System.out.println("生成json字符串"); StringBuffer words = new StringBuffer(); words.append("["); for (int i = 0; i 3; i++) {

书香代码 2317

java simple json_java.lang.String无法强制转换为org.json.simple.JSONObject simple-json

尝试使用google的simple-json解析一个简单的json时,我遇到了奇怪的问题.这是我的代码不起作用:String s = args[0].toString();JSONObject json = (JSONObject)new JSONParser().parse(s);当我执行时,它会给我异常java.lang.String无法强制转换为org.json.simple.JSONObj...

weixin_42502255的博客 389

Missing artifact org.json.simple:json-simple:jar:1.1.1

Missing artifact org.json.simple:json-simple:jar:1.1.1找不到json-simple-1.1.1.jar描述:该项目maven构建的,所以jar包都是maven来管理的问题分析:检查本地maven库是否下载了完整的jar,是否缺失?解决方法:下载json-simple-1.1.1.jar我的电脑,打开cmd 运行下列代码,下载到本地Maven库:...

别样的风采是我 7877

ClassNotFoundException: org.json.simple.parser.ContentHandler

Maven的pom.xml少了下面的依赖 <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency> <.

Mr.品梵的博客 1454

使用JSONObject.getString()时报错:Cannot resolve method ‘getString‘ in ‘JSONObject‘,详解JSONObject三种库的用法

通过以上对比可以发现,虽然这三种库都可以操作 JSON 数据,但它们的功能设计和使用场景各不相同: org.json.JSONObject 适合基础场景,方法直观易懂。 org.json.simple.JSONObject 功能最简单,需要更多手动操作。 cn.hutool.json.JSONObject 适合复杂项目,提供了更强的扩展能力。

RenGJ010617的博客 6738

几种常用的JSON解析工具的使用

目录 简介: (1)org.json的使用 (2)net.sf.json的使用 (3)json-simple的使用 (4)gson的使用 (5)jackson的使用 (6)fastjson的使用 简介: 现在越来越多的网站采用JSON来交换数据,在Json.org网站上,Java可以使用的解析Json的组件就有超过20种。 Json官网:http://json.org/ 页面往下拉,可以看到java板块的json类库: 其中gson,jackson,fastjson都是我们常用的工具类

ooooooooooooooxiaosu的博客 1463
上一篇: Ubuntu下安装python的torndb开发环境
下一篇: MySQL命令大全
北雨南萍
北雨南萍 领域专家: 操作系统技术领域 领域专家: 操作系统技术领域
博客等级 码龄20年 2665粉丝 453原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

北雨南萍

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值