一、json-lib所需的jar包:
json-lib.jar,commons-beanutils.jar,commons-collections.jar,commons-lang.jar,commons-logging.jar,ezmorph-1.0.6.jar(可直接在网上搜索下载)。
二、使用:
1、json字符串 <------> json
String jsonStr="{\"name\" : \"peter\",\"age\" : 25,\"address\" : \"广州\",\"weight\" : \"55.5\",\"handsome\" : true}"; //String------>json JSONObject jsonObject=JSONObject.fromObject(jsonStr); //json------>String String jsonString=jsonObject.toString();
2、java实体类 <------> json
public class User { private String name; private int age; private String address; private double weight; private boolean handsome; //省略构造和get/set方法 }
User user=new User("peter", 20, "广州", 55.5, true); //java实体类------>json JSONObject jsonObject=JSONObject.fromObject(user); //{"weight":55.5,"address":"广州","name":"peter","age":20,"handsome":true} System.out.println(jsonObject);
3、List <------> json
List<String> list=new ArrayList<String>(); list.add("QQQQQQ"); list.add("WWWWWW"); list.add("EEEEEE"); list.add("RRRRRR"); //List------>json JSONArray jsonArray=JSONArray.fromObject(list); //json------>List List<String> list3=(List)JSONArray.toCollection(jsonArray);
4、Map <------> json
Map<String, String> map=new HashMap<String, String>(); map.put("name", "peter"); map.put("sex", "Man"); map.put("age", "20"); //Map------json JSONObject jsonMap=JSONObject.fromObject(map); //json------>Map Map<String, String> mapJson=(Map)JSONObject.toBean(jsonMap, Map.class);
5、Set <------> json
Set<String> set=new HashSet<String>(); set.add("QQQQQQ"); set.add("wwwwww"); set.add("eeeeee"); //Set------>json JSONArray array=JSONArray.fromObject(set); //json------>Set Set<String> set1=new HashSet<String>(); for (Object object : array) { set1.add(object.toString()); } //报错:java.lang.ClassCastException Set<String> setJson=(Set<String>)JSONArray.toCollection(array,Set.class); //直接转List List<String> list=(List)JSONArray.toCollection(array);
时间: 2024-10-10 02:02:13