Java编程之JSON

来源:互联网 发布:php跨数据库查询 编辑:程序博客网 时间:2024/06/03 16:43

从Java数组或者集合中创建数组,最简单的办法就是通过静态工厂方法JSONArray。

boolean[] boolArray = new boolean[]{true,false,true};JSONArray jsonArray = JSONArray.fromObject(boolArray);System.out.println(jsonArray);//[true,false,true]
    List list = new ArrayList();    list.add("first");    list.add("second");    JSONArray jsonArray = JSONArray.fromObject(list);    System.out.println(jsonArray);//["first","second"]
JSONArray jsonArray = JSONArray.fromObject("['JSON','IS','GOOD']");System.out.println(jsonArray); //["JSON","IS","GOOD"]

从Map、JavaBean到JSON对象

  /*map对象到Java对象*/  Map map = new HashMap();  map.put("name", "json");  map.put("bool", Boolean.TRUE);  map.put("int", new Integer(1));  map.put("arr", new String[]{"b","a"});  map.put("func", "function(i){ return this.arr[i]}");  JSONObject jsonObject = JSONObject.fromObject(map);  //{"arr":["b","a"],"bool":true,"func":function(i){ return   //  this.arr[i]},"name":"json","int":1}  System.out.println(jsonObject);
public class MyBean {   private String name = "json";   private int pojoId = 1;   private char[] options = new char[]{'a','b'};   private String func1 = "function(i){return this.options[i];";   private JSONFunction func2 =new JSONFunction(new String[]{"i"},"return this.options[i];");   //省略getter、setter方法JSONObject jsonObject = JSONObject.fromObject(new MyBean());System.out.println(jsonObject);/*{"func1":"function(i){return this.options[i];","func2":function(i){ return this.options[i]; },"name":"json","options":["a","b"],"pojoId":1}*/
0 0
原创粉丝点击