1.依赖
创建maven项目,引入依赖
<!-- fastjson--> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> </dependency>
2.简单使用
2.1 简单Java类转json字符串
String UserJson = JSON.toJSONString(user);
2.2 List<Object>转json字符串
User user1 = new User("zhangsan", "123123"); User user2 = new User("lisi", "321321"); List<User> users = new ArrayList<User>(); users.add(user1); users.add(user2); String ListUserJson = JSON.toJSONString(users);
2.3 复杂Java类转json字符串
UserGroup userGroup = new UserGroup("userGroup", users); String userGroupJson = JSON.toJSONString(userGroup);
2.4 json字符串转Java对象
String jsonStr1 = "{'password':'123456','username':'dmego'}"; User user = JSON.parseObject(jsonStr1, User.class);
2.5 json字符串转List<Object>对象
String jsonStr2 = "[{'password':'123123','username':'zhangsan'},{'password':'321321','username':'lisi'}]"; List<User> users = JSON.parseArray(jsonStr2, User.class);
2.6 json字符串转复杂Java对象
String jsonStr3 = "{'name':'userGroup','users':[{'password':'123123','username':'zhangsan'},{'password':'321321','username':'lisi'}]}"; UserGroup userGroup = JSON.parseObject(jsonStr3, UserGroup.class);
2.7 map转对象
String mapString = JSONObject.toJSONString(map); Hospital hospital = JSONObject.parseObject(mapString, Hospital.class);