迫使Jackson将特定属性反序列化为特定的原始类型

时间:2018-07-31 04:10:53

标签: java json jackson jackson-databind

我正在使用jackson 2.9.6,我有一个要序列化和反序列化的对象。这是Post

Post.java

public class Post  extends GenericJson {

    private Long id;
    private String name;
    private int count;

    private List<Comment> commentList;

    // Getter and setter

}

public class Comment  extends GenericJson{

    private Long id;
    private String text;
    private int count;

    // Getter and setter

}

JSON数据

{
    "id" : 123,
    "name" : "azeem",
    "count" : 1,
    "commentList" : [
        {
            "id" : 312,
            "text" : "simple comment",
            "count" : 3
        },
        {
            "id" : 31221231231231,
            "text" : "simple comment 2",
            "count" : 1
        }
    ]
},

    "id" : 123127877186786,
    "name" : "arfan",
    "count" : 5,
    "commentList" : [
        {
            "id" : 312,
            "text" : "simple comment",
            "count" : 3
        },
        {
            "id" : 31221231231231,
            "text" : "simple comment 2",
            "count" : 1
        }
    ]
}

我正在使用ObjectMapper进行读写,就像这样。

用于写入

 objectMapper.writeValue(fileDir, postObject);

供阅读

 objectMapper.readValue(savedFileDir, Post.class); // Error can't cast int to long

您可以看到错误无法将int转换为长帖子['id'] ,并且在commentList中也是如此,这是因为在 Json Data 第一个id 123 ,因此jackson将其视为int,并尝试将其保存在Long id

我在 StackOverFlow 上看到了一个使用DeserializationFeature.USE_LONG_FOR_INTS的答案,但是我无法使用它,因为在count中还有另一个属性int我需要它。

如果我使用DeserializationFeature.USE_LONG_FOR_INTS,则会显示错误消息 Long无法转换为int post ['count'] ,并且与commentList

相同

我想问问我有什么方法可以将特定的属性转换为特定的原始类型。例如,在这种情况下,我希望idLong的{​​{1}}的属性始终都在Post中。其他所有属性都很好。

能不能让我知道我该怎么做?

更新

CommentPost类是自动生成的,不能在这些文件中进行任何更改。实际上,我正在使用 Google云端点v2 ,这些文件是 由云端点生成。云端点使用相同的Comment库将json数据转换为这些类对象,但我不知道它们会这样做。

1 个答案:

答案 0 :(得分:0)

您可以使用@JsonSetter解决此问题。

public class Post {

private Long id;
private String name;
private int count;

private List<Comment> commentList;

// Getter and setter


@JsonSetter
public void setId(int id) {
    this.id = (long) id;
}
}

您的json中有一个问题。 ,丢失。

  

“计数”:1

     

“计数”:5