package com.main; import java.util.Date; public class User { private String name; private Integer age; private Date birthday; private String email; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Double getPercent() { return this.age / 100.0; } public String getPreName() { return "Pre" + this.name; } }
User user = new User(); user.setName("小民"); user.setEmail("[email protected]"); user.setAge(20); SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd"); try { user.setBirthday(dateformat.parse("1996-10-01")); } catch (ParseException e) { e.printStackTrace(); } /** * ObjectMapper是JSON操作的核心,Jackson的所有JSON操作都是在ObjectMapper中实现。 * ObjectMapper有多个JSON序列化的方法,可以把JSON字符串保存File、OutputStream等不同的介质中。 * writeValue(File arg0, Object arg1)把arg1转成json序列,并保存到arg0文件中。 * writeValue(OutputStream arg0, Object arg1)把arg1转成json序列,并保存到arg0输出流中。 * writeValueAsBytes(Object arg0)把arg0转成json序列,并把结果输出成字节数组。 * writeValueAsString(Object arg0)把arg0转成json序列,并把结果输出成字符串。 */ ObjectMapper mapper = new ObjectMapper(); String json = null; try { json = mapper.writeValueAsString(user); } catch (JsonProcessingException e) { e.printStackTrace(); } System.out.println(json); //{"name":"小民","age":20,"birthday":844099200000,"email":"[email protected]","percent":0.2,"preName":"Pre小民"} System.out.println("--------------------------------------------"); user.setEmail(null); try { json = mapper.writeValueAsString(user);//以get方法为准 } catch (JsonProcessingException e) { e.printStackTrace(); } System.out.println(json); //{"name":"小民","age":20,"birthday":844099200000,"email":null,"percent":0.2,"preName":"Pre小民"} System.out.println("--------------------------------------------"); Gson gson = new Gson();//以非空属性为准 System.out.println(gson.toJson(user)); //{"name":"小民","age":20,"birthday":"Oct 1, 1996 12:00:00 AM"} System.out.println("--------------------------------------------"); System.out.println(JSON.toJSONString(user));//以get方法且非空属性为准 //{"age":20,"birthday":844099200000,"name":"小民","percent":0.2,"preName":"Pre小民"}