jazz's blog

Jsonp Api Demo in Java

Java平台的JSON处理的API的演示

  1. JSON是一种轻量级数据交换格式,rails4的 respond_to do |format|拿掉xml以json取代,2013 了,再拿xml当default API就不是有一点的out了

  2. JSR-353的参考实现JSON-P将作为即将发布的JavaEE 7的一部分

  3. 以下代码演示JSONP的读写API

     import java.io.*;
    
     import javax.json.*;
     import javax.json.stream.*;
     import javax.json.stream.JsonParser.*;
    
     public class JsonDemo {
         private String address = "./json_demo.js";
    
         public static void main(String[] args) throws Exception {
             JsonDemo demo = new JsonDemo();
             demo.write();
             demo.read();
         }
    
         public void write() throws Exception{
             JsonBuilderFactory factory = Json.createBuilderFactory(null);
             JsonArray jsonArray = factory.createArrayBuilder()
                 .add(factory.createObjectBuilder()
                     .add("username", "zhijia,.zhang")
                     .add("email", "jiahut@gmail.com"))
                 .add(factory.createObjectBuilder()
                     .add("username", "lishi")
                     .add("email", "lishi@demo.com"))
                 .build();
             try (JsonWriter jsonWriter = Json.createWriter(new FileWriter(address))) {
                   jsonWriter.writeArray(jsonArray);
             }
         }
    
         public void read() throws Exception{
             JsonParserFactory factory = Json.createParserFactory(null);
             StringBuffer stb = new StringBuffer();
             String str = null;
    
             try(BufferedReader rd = new BufferedReader(new FileReader(address))){
                 while((str = rd.readLine()) != null){
                     stb.append(str);
                 }
             }
    
             JsonParser parser = factory.createParser(new StringReader(stb.toString()));
             while (parser.hasNext()) {
               Event event = parser.next();
               switch (event) {
                 case KEY_NAME: {
                   System.out.print(parser.getString() + "="); break;
                 }
                 case VALUE_STRING: {
                   System.out.println(parser.getString()); break;
                 }
               } // end switch
             }// end while
         }
     }
    
  4. 命令行下编译与运行

    • 请先下载jsonp的jar到当前目录
    • 请使用java7或以上版本

    • 编译 javac -cp .;javax.json-1.0-fab.jar JsonDemo.java

    • 运行 java -cp .;javax.json-1.0-fab.jar JsonDemo

    • 当然你也可以打开产生的json_demo.js 文件看看生成的内容