Java

Jackson의 모든 것 - 다형성 편

Jaime.Lee 2019. 11. 21. 16:27
모든 소스는 여기서 확인하실 수 있습니다.

 

Jackson에서 다형성 처리를 위하여 아래와 같은 애노테이션을 사용합니다.

 

  • @JsonTypeInfo: 직렬화 시 포함할 타입 정보의 세부 사항을 나타냅니다.
  • @JsonSubTypes: 애노테이션이 달린 타입의 하위 타입을 지정합니다.
  • @JsonTypeName: 애노테이션이 달린 타입의 논리적 이름을 지정합니다.
package io.lcalmsky.jackson.domain;

import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;

public class Zoo {
    public Animal animal;

    public Zoo(Animal animal) {
        this.animal = animal;
    }

    @JsonTypeInfo(
            use = JsonTypeInfo.Id.NAME,
            include = JsonTypeInfo.As.PROPERTY,
            property = "type")
    @JsonSubTypes({
            @JsonSubTypes.Type(value = Dog.class, name = "dog"),
            @JsonSubTypes.Type(value = Cat.class, name = "cat")
    })
    public static class Animal {
        public String name;
    }

    @JsonTypeName("dog")
    public static class Dog extends Animal {
        public double barkVolume;

        public Dog(String name) {
            super.name = name;
        }
    }

    @JsonTypeName("cat")
    public static class Cat extends Animal {
        public int lives;
        boolean likesCream;
    }
}

 

package io.lcalmsky.jackson.domain;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;

import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;

public class PolymorphicTests {
    @Test
    public void WhenPolymorphicBeanProvided_ThenSerialize_ExpectCorrect() throws JsonProcessingException {
        // when
        Zoo.Dog dog = new Zoo.Dog("lacy");
        Zoo zoo = new Zoo(dog);

        // then
        String json = new ObjectMapper().writeValueAsString(zoo);

        // expected
        System.out.println(json);
        assertThat(json, containsString("type"));
        assertThat(json, containsString("dog"));
    }
}

 

Testing started at 4:25 PM ...
> Task :jackson:cleanTest
> Task :jackson:compileJava
> Task :jackson:processResources NO-SOURCE
> Task :jackson:classes
> Task :jackson:compileTestJava
> Task :jackson:processTestResources NO-SOURCE
> Task :jackson:testClasses
> Task :jackson:test
{"animal":{"type":"dog","name":"lacy","barkVolume":0.0}}
BUILD SUCCESSFUL in 2s
4 actionable tasks: 4 executed
4:25:03 PM: Tasks execution finished ':jackson:cleanTest :jackson:test --tests "io.lcalmsky.jackson.domain.PolymorphicTests.WhenPolymorphicBeanProvided_ThenSerialize_ExpectCorrect"'.