Programing/Java

Jackson ObjectMapper

BUST 2018. 10. 25. 22:44

Jackson ObjectMapper

  • Java에서 Json를 다룰때 주로 사용하는 Jackson ObjectMapper에 대해 정리를 해보자.

Gradle

compile "com.fasterxml.jackson.core:jackson-databind:2.9.4"


ObjectMapper를 이용한 Json Write, Read


public class Car {
    private String color;
    private String type;
}


Json Write

ObjectMapper objectMapper = new ObjectMapper();

Car car = new Car("yellow", "bmw");


String carAsString = objectMapper.writeValueAsString(car);


Json Read

String json = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
Car car = objectMapper.readValue(json, Car.class); 


Annotation

@JsonProperty

public class MyBean {
    public int id;
    private String name;
 
    @JsonProperty("name")
    public void setTheName(String name) {
        this.name = name;
    }
 
    @JsonProperty("name")
    public String getTheName() {
        return name;
    }
}


@JsonSerialize

public class Event {
    public String name;
 
    @JsonSerialize(using = CustomDateSerializer.class)
    public Date eventDate;
}


@JsonDeserialize

public class Event {
    public String name;
 
    @JsonDeserialize(using = CustomDateDeserializer.class)
    public Date eventDate;
}


@JsonIgnore

public class BeanWithIgnore {

    @JsonIgnore

    public int id;

 

    public String name;

}


@JsonIgnoreProperties({ "id" })

@JsonIgnoreProperties({ "id" })

public class BeanWithIgnore {

    public int id;

    public String name;

}


@JsonAnyGetter

public class ExtendableBean {

    public String name;

    private Map<String, String> properties;

 

    @JsonAnyGetter

    public Map<String, String> getProperties() {

        return properties;

    }

}

{

    "name":"My bean",

    "attr2":"val2",

    "attr1":"val1"

}


@JsonAnySetter

public class ExtendableBean {

    public String name;

    private Map<String, String> properties;

 

    @JsonAnySetter

    public void add(String key, String value) {

        properties.put(key, value);

    }

}


public class ExtendableBean {

    public String name;

    private Map<String, String> properties;

 

    @JsonAnySetter

    public void add(String key, String value) {

        properties.put(key, value);

    }

}


'Programing > Java' 카테고리의 다른 글

URI  (0) 2018.11.22
Queue 자료 구조  (0) 2018.11.12
Java Jdbc를 이용한 데이터베이스 접근하기  (0) 2018.10.23
Guava Eventbus @AllowConcurrentEvents  (0) 2018.10.10
CompletableFuture  (0) 2018.09.15