Why doesn't jackson save types?

时间:2017-08-04 13:07:11

标签: json java-8 jackson

I am trying to have jackson save types along with values, as follows:

@Test
public void doesNotSaveNestedTypes() throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.JAVA_LANG_OBJECT, JsonTypeInfo.As.WRAPPER_ARRAY);
    mapper.registerSubtypes(MyResultList.class, MyResult.class);
    String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(getMyResultList());
    System.out.println(json);
}

private MyResultList getMyResultList(){
    List<MyResult> myList = new ArrayList<>(3);
    myList.add(new MyResult(1));
    myList.add(new MyResult(2));
    return new MyResultList(myList);
}

The types are not in the generated json:

{
  "myResults" : [ {
    "r" : 1
  }, {
    "r" : 2
  } ]
}

Here are the classes involved in this example:

public class MyResult {
    private int r;
    public MyResult(){}
    public MyResult(int r){this.r = r;}

    public int getR() {
        return r;
    }

    @Override
    public String toString() {
        return "MyResult{" +
                "r=" + r +
                '}';
    }
}

import lombok.*;

import java.util.List;

@Data
@RequiredArgsConstructor
@EqualsAndHashCode
@ToString
public class MyResultList {
    @NonNull
    private final List<MyResult> myResults;
}

Based on documentation, I was expecting to get the following:

{
  ["org.mypackage.MyResultList", {"myResults":  [ 
["org.mypackage.MyResults", {
    "r" : 1
  }, 
     (snip)

I have tried removing lombok attributes - that does not help at all. How to make jackson save types?

1 个答案:

答案 0 :(得分:1)

问题是JAVA_LANG_OBJECT。在您的情况下,您需要NON_FINAL。以下是docs

中对这些选项的说明
  • JAVA_LANG_OBJECT:仅影响Object.class
  • 类型的属性
  • OBJECT_AND_NON_CONCRETE:影响Object.class和所有非具体类型(抽象类,接口)
  • NON_CONCRETE_AND_ARRAYS:与上面相同,所有相同的数组类型(直接元素都是非具体类型或Object.class)
  • NON_FINAL:影响所有未声明为'final'的类型,以及非最终元素类型的数组类型。

使用NON_FINAL将导致此输出:

[ "org.mypackage.MyResultList", {
  "myResults" : [ "java.util.ArrayList", [ [ "org.mypackage.MyResult", {
    "r" : 1
  } ], [ "JacksonBinding.MyResult", {
    "r" : 2
  } ] ] ]
} ]

无法在没有注释的情况下看到输出"java.util.ArrayList"的方法。