fastjson
对象与Json互转
public class JsonServlet04 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("=====对象转Json=====");
User user = new User("张三","北京",true);
String json = JSON.toJSONString(user);
System.out.println(json);
System.out.println("=====Json转对象=====");
String json01 = "{\"address\":\"北京\",\"name\":\"张三\",\"sex\":true}";
User user01 = JSON.parseObject(json01,User.class);
System.out.println(user01);
}
}
List与Json互转
public class JsonServlet05 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("=====List转Json=====");
//创建List对象
List<User> list = new ArrayList<User>();
list.add(new User("UZI","China",true));
list.add(new User("MLXG","China",true));
list.add(new User("doinb","韩国",true));
String json = JSON.toJSONString(list);
System.out.println(json);
System.out.println("=====Json转List=====");
String json1 = "[{\"name\":\"UZI\",\"address\":\"China\",\"sex\":true},"
+ "{\"name\":\"MLXG\",\"address\":\"China\",\"sex\":true},"
+ "{\"name\":\"doinb\",\"address\":\"韩国\",\"sex\":true}]";
List<User> list1 = JSON.parseArray(json1,User.class);
for(User u:list1) {
System.out.println(u);
}
}
}
Map与Json互转
public class JsonServlet06 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("=====Map转Json=====");
Map<String,Object> map = new HashMap<>();
map.put("id", "001");
map.put("user", new User("doinb","韩国",true));
String json1 = JSON.toJSONString(map);
System.out.println(json1);
System.out.println("=====Json转Map=====");
String json01 = "{\"id\":\"001\",\"user\":{\"name\":\"doinb\",\"address\":\"韩国\",\"sex\":true}}";
Map<String,Object> map1 = JSON.parseObject(json01,map.getClass());
for(String key:map1.keySet()) {
System.out.println(key+":"+map1.get(key));
}
}
}