Home > Blockchain >  Jackson objectMapper gives different object for same json
Jackson objectMapper gives different object for same json

Time:10-29

I'm passing a json to objectmapper. The JSON string looks like this:

{          
  "id": "ID1",
  "identifier" : "XYZ",
  "data": [
  {
    "id": "sampleParentID",
    "childrenElements": [
    {
      "id" : "sampleChildID",
      "content" : "sample child content",  
    }
    ]
  }
  ]
}
 val objectMapper = ObjectMapper().registerModule(KotlinModule())
 val obj: Object1 = objectMapper.readValue(jsonString)

My class looks something like this :

data class Object 1 (
 var id : String? = null,
 var identifier : String? = null,
 var data: MutableList<Element>? = null,

){
 // some functions
}
class Element (
 var id : String?= null
 var content : String? = null
 var children: List<Element>? = listOf(),

) {
 // som functions
}

From obj, data field is nested which is an object itself. I want to get hashCode of data so I do obj.data.hashCode(). Let's say 12345 gets generated.

I store this in the database. Now, let's say the user sends another request with exactly the same JSON, again the JSON gets converted into an object from which I extract the data field and now when I do obj.data.hashCode(), 12345 is not generated, rather some other number gets generated.

Is this behavior expected? If yes, what is the workaround?

Update : Added classes description.

CodePudding user response:

Given that your Element class is not a data class (in this case you would get a hashCode() method implementation based on all class properties) you will need to write the hashCode() method yourself so that the default one (based on object memory reference) is not used and you get rid of the behaviour you are currently facing.

  • Related