清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>
使用gson.jar处理Json比较简单,先用new Gson()获取一个Gson实例,执行toJson()方法把一个对象转换成Json,执行fromJson()方法将Json转换成对象。Demo如下:
Gson gson = new Gson(); // 从Bean生成Json User user1 = new User(); user1.setId("111"); user1.setName("111name"); String user1Json = gson.toJson(user1); //输出:{"id":"111","name":"111name"} // 从Json生成Bean String user2Json = "{'id':'112','name':'112name'}"; User user2 = gson.fromJson(user2Json, User.class ); //输出: User [id=112, name=112name] //从Map生成Json HashMap<String, String> mapJson = new HashMap<String, String>(); mapJson.put("id", "113"); mapJson.put("name", "113name"); String mapJsonStr = gson.toJson(mapJson); //输出:{"name":"113name","id":"113"} //从List生成Json ArrayList<User> userList = new ArrayList<User>(); User user1 = new User(); user1.setId("114"); user1.setName("114name"); User user2 = new User(); user2.setId("115"); user2.setName("115name"); userList.add(user1); userList.add(user2); String listJsonStr = gson.toJson(userList); //输出:[{"id":"114","name":"114name"},{"id":"115","name":"115name"}]