Json-simple-encode-jsonarray

提供:Dev Guides
移動先:案内検索

JSON.simple-JSONArrayのエンコード

JSON.simpleを使用して、次の方法を使用してJSON配列をエンコードできます-

  • * JSON配列のエンコード-ストリングへ*-単純なエンコード。
  • * JSON配列のエンコード-ストリーミング*-出力はストリーミングに使用できます。
  • * JSON配列のエンコード-リストの使用*-リストを使用したエンコード。
  • * JSON配列のエンコード-リストとストリーミングの使用*-リストを使用したエンコードとストリーミング。

次の例は、上記の概念を示しています。

import java.io.IOException;
import java.io.StringWriter;
import java.util.LinkedList;
import java.util.List;

import org.json.simple.JSONArray;
import org.json.simple.JSONValue;

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

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

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

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

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

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

      jsonText = JSONValue.toJSONString(list1);
      System.out.println("\nEncode a JSON Array - Using List");
      System.out.print(jsonText);

      out = new StringWriter();
      JSONValue.writeJSONString(list1, out);
      jsonText = out.toString();
      System.out.println("\nEncode a JSON Array - Using List and Stream");
      System.out.print(jsonText);
   }
}

出力

Encode a JSON Array - to String
["foo",100,1000.21,true,null]
Encode a JSON Array - Streaming
["foo",100,1000.21,true,null]
Encode a JSON Array - Using List
["foo",100,1000.21,true,null]
Encode a JSON Array - Using List and Stream
["foo",100,1000.21,true,null]