一、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);
三、CRUD:
1、查询数据:
//对比age和weight数据 String jsonStr="{"name" : "peter","age" : 25,"address" : "广州","weight" : "55.5","handsome" : true}"; //String------>json JSONObject jsonObject=JSONObject.fromObject(jsonStr); String name=jsonObject.getString("name"); String age=jsonObject.getString("age"); String address=jsonObject.getString("address"); String handsome=jsonObject.getString("handsome"); //正常输出25 int age1=jsonObject.getInt("age"); long age2=jsonObject.getLong("age"); double age3=jsonObject.getDouble("age"); //int和long输出55,double输出55.5 int weight1=jsonObject.getInt("age"); long weight2=jsonObject.getLong("age"); double weight3=jsonObject.getDouble("age"); boolean handsome1=jsonObject.getBoolean("handsome");
for (int i = 0; i < jsonArray.size(); i++) { System.out.println(jsonArray.get(i)); }
2、增加数据
jsonObject.put("height", 170);
jsonArray.add("MMMMMM");
3、删除数据:
jsonObject.remove("height");
//index从0开始 jsonArray.remove(index);
4、修改数据:
//重置数据即可 jsonObject.put("age", 20);
for (int i = 0; i < jsonArray.size(); i++) { if("QQQQQQ".equals(jsonArray.get(i))){ jsonArray.remove(i); jsonArray.add("qqqqqq"); } }