当前位置: 代码迷 >> 综合 >> java jackson json demo 入门1
  详细解决方案

java jackson json demo 入门1

热度:78   发布时间:2023-10-10 21:26:17.0

忽略该属性
@JsonIgnore
格式化属性
@JsonFormat(pattern = “yyyy-MM-dd”)

package com.example.test;import com.example.domain.Person;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;public class JacksonTest {
    // java对象转json@Testpublic void test1() throws IOException {
    Person person = new Person();person.setName("刘强东");person.setAge(23);person.setGender("男");// 创建jackson核心对象ObjectMapper mapper = new ObjectMapper();String s = mapper.writeValueAsString(person);// 写入文件// mapper.writeValue(new File("e://app/1.txt"),person);// mapper.writeValue(new FileWriter("e://app/1.txt"),person);System.out.println(s);}@Testpublic void test2() throws JsonProcessingException {
    Person person = new Person();person.setName("刘强东");person.setAge(23);person.setGender("男");person.setBirthday(new Date());ObjectMapper objectMapper = new ObjectMapper();String s = objectMapper.writeValueAsString(person);System.out.println(s);}}
package com.example.domain;import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;import java.util.Date;public class Person {
    private String name;private int age;private String gender;// 忽略该属性// @JsonIgnore@JsonFormat(pattern = "yyyy-MM-dd")private Date birthday;public Date getBirthday() {
    return birthday;}public void setBirthday(Date birthday) {
    this.birthday = birthday;}public String getName() {
    return name;}public void setName(String name) {
    this.name = name;}public int getAge() {
    return age;}public void setAge(int age) {
    this.age = age;}public String getGender() {
    return gender;}public void setGender(String gender) {
    this.gender = gender;}@Overridepublic String toString() {
    return "Person{" +"name='" + name + '\'' +", age=" + age +", gender='" + gender + '\'' +'}';}
}
  相关解决方案