(一)基本对象转换
代码:
@Test
public void test01() throws Exception {
Person p = new Person();
p.setAge(10);
p.setGender("男");
p.setUsername("Alworm");
p.setBirthday(new Date());
ObjectMapper mapper = new ObjectMapper();
String s = mapper.writeValueAsString(p);
System.out.println(s);
//将对象转换为json,并且保存到文件中
// mapper.writeValue(new File("e://a.txt"),p);
// mapper.writeValue(new FileWriter("e://b.txt"),p);
}
Person 对象
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.Date;
public class Person {
private String username;
private Integer age;
private String gender;
@JsonFormat(pattern = "yyyy-MM-dd")
// @JsonIgnore //排除,忽略
private Date birthday;
@Override
public String toString() {
return "Person{" +
"username='" + username + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
", birthday=" + birthday +
'}';
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
(二)列表对象转换为JSON格式
代码:
@Test
public void test02() throws Exception {
Person p = new Person();
p.setAge(10);
p.setGender("男");
p.setUsername("Alworm");
p.setBirthday(new Date());
Person p1 = new Person();
p1.setAge(10);
p1.setGender("男");
p1.setUsername("Alworm");
p1.setBirthday(new Date());
Person p2 = new Person();
p2.setAge(10);
p2.setGender("男");
p2.setUsername("Alworm");
p2.setBirthday(new Date());
List<Person> list = new ArrayList<Person>();
list.add(p);
list.add(p1);
list.add(p2);
ObjectMapper mapper = new ObjectMapper();
String s = mapper.writeValueAsString(list);
System.out.println(s);
}
(三)map转换为JSON格式
代码
@Test
public void test03() throws JsonProcessingException {
Map<String,Object> map = new HashMap<>();
map.put("username","ALworm");
map.put("age",23);
map.put("gender","男");
ObjectMapper mapper = new ObjectMapper();
String s = mapper.writeValueAsString(map);
System.out.println(s);
}