Forcing Jackson to deserialize specific property to specific primitive type

Multi tool use
Multi tool use
The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


Forcing Jackson to deserialize specific property to specific primitive type



I'm using jackson 2.9.6 I have a object that I want to serialize and Deserialize. Here is a class Post


jackson 2.9.6


Post



Post.java


public class Post {

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

private List<Comment> commentList;

// Getter and setter

}

public class Comment{

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

// Getter and setter

}



JSON Data


{
"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
}
]
}



I'm using ObjectMapper to read and write, like this.


ObjectMapper



For Write


objectMapper.writeValue(fileDir, postObject);



For Read


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



As you can see there is error can't cast int to long post['id'] and same in commentList this is because in Json Data first id is 123 So jackson consider it as int and try to save it on Long id


commentList


id


jackson


int


Long id



I see an answer on StackOverFlow that use DeserializationFeature.USE_LONG_FOR_INTS But I can't use it because there is another property count which I need it in int.


DeserializationFeature.USE_LONG_FOR_INTS


count


int



If I use DeserializationFeature.USE_LONG_FOR_INTS it show me error that Long can't cast to int post['count'] and same as commentList


DeserializationFeature.USE_LONG_FOR_INTS


commentList



I want to ask that Is there any way I can convert specific property to specific primitive type. For example in this I want id property always in Long in both Post and Comment. Other all properties are fine.


id


Long


Post


Comment



Can you please let me know how can I do that.





Does id need to be the wrapper type? Can you change it to the primitive long?
– ernest_k
5 mins ago


id


long









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

vs,6s,z1mhG CfzfZrnuTiiXOn57mJ0IHVa6va1k3T,X0joowra,J vvmiWecLHubqOLCw UqrPr2ZfMBDyavCigrQG5ZxdtQWFq j NO,6
oUtcNhb9pjhvSx,byE7q

Popular posts from this blog

Makefile test if variable is not empty

Visual Studio Code: How to configure includePath for better IntelliSense results

Will Oldham