public static void main(String args[]){
JSONObject jsonObject;
JSONArray jsonArray;
//数组转化为json
String[] tempArry=new String[]{"a","b","c"};
jsonArray=JSONArray.fromObject(tempArry);
System.out.println(jsonArray.toString());//打印出来的结果:["a","b","c"]
//list转换为json
List<String> tempList=new ArrayList<String>();
tempList.add("a");
tempList.add("b");
tempList.add("c");
JSONArray listJsonArray = JSONArray.fromObject(tempList);
System.out.println(listJsonArray.toString());//打印出来的结果:["a","b","c"]
//List 里面有对象
List<User> objectList=new ArrayList<User>();
User bean =new User();
bean.setUserId("id1");
bean.setUserName("name1");
objectList.add(bean);
bean =new User();
bean.setUserId("id2");
bean.setUserName("name2");
objectList.add(bean);
JSONArray json = JSONArray.fromObject(objectList);
System.out.println(json.toString());//打印结果:[{"userId":"id1","userName":"name1"},{"userId":"id2","userName":"name2"}]
//对象转换为json
User bean2 =new User();
bean2.setUserId("id1");
bean2.setUserName("name1");
jsonObject = JSONObject.fromObject(bean2);
System.out.println(jsonObject.toString());//打印结果:{"userId":"id1","userName":"name1"}
//Map 转换为json
Map<String,String> map= new HashMap<String,String>();
map.put("key1", "value1");
map.put("key2", "value2");
jsonObject = JSONObject.fromObject(map);
System.out.println(jsonObject);//打印结果:{"key2":"value2","key1":"value1"}
//map里面有list
Map<String,List> listMap= new HashMap<String,List>();
List<User> mapList=new ArrayList<User>();
User bean1 =new User();
bean1.setUserId("id1");
bean1.setUserName("name1");
mapList.add(bean);
listMap.put("key1", mapList);
bean1 =new User();
bean1.setUserId("id2");
bean1.setUserName("name2");
mapList.add(bean);
listMap.put("key1", mapList);
jsonObject = JSONObject.fromObject(listMap);
System.out.println(jsonObject.toString());//打印结果:{"key1":[{"userId":"id1","userName":"name1"},{"userId":"id2","userName":"name2"}]}
}
json解析的对象主要有2个JSONArray 和JSONObject
JSONArray 主要转换Object[] 和Collection
JSONObject主要解析对象和Map