JSONObject,JSONArray使用手册

jopen 8年前

这两个是官网的API

JSONObject API

JSONArray API

里面有这两个类的所有方法,是不可多得的好材料哦~

配合上面的API,大家再看下这段代码,就会大有收获了~
    import net.sf.json.JSONArray;          import net.sf.json.JSONObject;          import java.util.*;          /**         *         * @author derek         */          public class JavaTest {              public static void main(String[] args){                   JSONObject obj=new JSONObject();                 obj.put("derek","23");                 obj.put("dad", "49");                 obj.put("mom", "45");                 System.out.println("通过构造器的方式创建的JSONObject对象:"+obj);                                  Map<String,String> map=new LinkedHashMap<>();                 map.put("derek","23");                 map.put("dad", "49");                 map.put("mom", "45");                 System.out.println("通过fromObject方法将map对象转换为JSONObject对象:"+JSONObject.fromObject(map));                                  JSONArray arr=new JSONArray();                 arr.add(0,"derek");                 arr.add(1,"dad");                 arr.add(2,"mom");                 System.out.println("通过构造器的方式创建的JSONArray:"+arr);                                  ArrayList<String> list=new ArrayList<>();                 list.add("derek");                 list.add("dad");                 list.add("mom");                 System.out.println("通过fromObject方法将Arraylist对象转换为JSONArray对象:"+JSONArray.fromObject(list));                                  System.out.println("将HashMap对象通过fromObject方法转换为JSONArray对象"+JSONArray.fromObject(map));                                  String str="{\"derek\":23,\"dad\":49,\"mom\":45}";                 System.out.println("解析之后的JSON对象:"+JSONObject.fromObject(str));                                  //遍历输出                 Iterator<String> it=obj.keys();                 while(it.hasNext()){                     String key=it.next();                     System.out.println(key+":"+obj.get(key));                 }              }                        }    

运行结果如下:

通过构造器的方式创建的JSONObject对象:{"derek":"23","dad":"49","mom":"45"}
通过fromObject方法将map对象转换为JSONObject对象:{"derek":"23","dad":"49","mom":"45"}
通过构造器的方式创建的JSONArray:["derek","dad","mom"]
通过fromObject方法将Arraylist对象转换为JSONArray对象:["derek","dad","mom"]
将HashMap对象通过fromObject方法转换为JSONArray对象[{"derek":"23","dad":"49","mom":"45"}]
解析之后的JSON对象:{"derek":23,"dad":49,"mom":45}
derek:23
dad:49
mom:45


来自:http://blog.csdn.net/exceptional_derek/article/details/18727489