📜  JSON.simple-编码JSONObject

📅  最后修改于: 2020-11-16 07:18:04             🧑  作者: Mango


使用JSON.simple,我们可以使用以下方式对JSON对象进行编码-

  • 将JSON对象编码-字符串-简单编码。

  • 编码JSON对象-流-输出可用于流。

  • 编码JSON对象-使用Map-通过保留顺序进行编码。

  • 编码JSON对象-使用Map和Streaming-通过保留顺序和流进行编码。

以下示例说明了上述概念。

import java.io.IOException;
import java.io.StringWriter;
import java.util.LinkedHashMap;
import java.util.Map;

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

class JsonDemo {
   public static void main(String[] args) throws IOException {
      JSONObject obj = new JSONObject();
      String jsonText;

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

      System.out.println("Encode a JSON Object - to String");
      System.out.print(jsonText);

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

      System.out.println("\nEncode a JSON Object - Streaming");       
      System.out.print(jsonText);

      Map obj1 = new LinkedHashMap();
      obj1.put("name", "foo");
      obj1.put("num", new Integer(100));
      obj1.put("balance", new Double(1000.21));
      obj1.put("is_vip", new Boolean(true));

      jsonText = JSONValue.toJSONString(obj1); 
      System.out.println("\nEncode a JSON Object - Preserving Order");
      System.out.print(jsonText);

      out = new StringWriter();
      JSONValue.writeJSONString(obj1, out); 
      jsonText = out.toString();
      System.out.println("\nEncode a JSON Object - Preserving Order and Stream");
      System.out.print(jsonText);
   }
}

输出

Encode a JSON Object - to String
{"balance":1000.21,"is_vip":true,"num":100,"name":"foo"}
Encode a JSON Object - Streaming
{"balance":1000.21,"is_vip":true,"num":100,"name":"foo"}
Encode a JSON Object - Preserving Order
{"name":"foo","num":100,"balance":1000.21,"is_vip":true}
Encode a JSON Object - Preserving Order and Stream
{"name":"foo","num":100,"balance":1000.21,"is_vip":true}