Forcing Jackson to deserialize specific property to specific primitive type

515 views
Skip to first unread message

Azeem Haider

unread,
Jul 31, 2018, 12:47:37 AM7/31/18
to jackson-user

I'm using jackson 2.9.6 I have a object that I want to serialize and Deserialize. Here is a class 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.


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


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.


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

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.


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


Post and Comment class is auto generate and can't make any changes in these files. Actually I'm using Google cloud endpoints v2 these files are generated by cloud endpoint. Cloud endpoints use the same jackson lib to convert json data into these class object but I don't know they do it.


Azeem Haider

unread,
Jul 31, 2018, 1:29:32 AM7/31/18
to jackson-user
These classes are extends from GenericJson Post extends GenericJson and Comment extends GenericJson
And there is one syntax error in json data put the (,) after count. I'm reply because I didn't find any way to edit my question
Reply all
Reply to author
Forward
0 new messages