2

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.

Kancha
  • 409
  • 1
  • 3
  • 11
  • 1
    Can you please add the classes of your model to which you are mapping the JSON? It really depends on how `hashCode()` was implemented. – João Dias Oct 28 '21 at 09:35
  • Hey. Added the classes. Should I declare something differently? – Kancha Oct 28 '21 at 10:13
  • 2
    Did you implement `hashCode()` for `Element`? If not, then each instance generates a different hash code, even if it has the same contents. Also, if you mean to identify objects using `hashCode()` then remember this value is not unique. Collisions are rare, but it is possible that objects with different contents have the same hash code. – broot Oct 28 '21 at 10:15
  • And if you store many objects like this in the database, probability of collisions greatly increases due to [birthday paradox](https://en.wikipedia.org/wiki/Birthday_problem). – broot Oct 28 '21 at 10:23
  • 1
    Right. I am not implementing my own `hashCode()` method. I think will have to write a custom `hashCode()` function. Thanks! – Kancha Oct 28 '21 at 10:25
  • IntelliJ can generate `hashCode()` and `equals()` for you automatically. Or, if you can turn `Element` into data class, it will get it for free. – broot Oct 28 '21 at 10:27

1 Answers1

1

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.

João Dias
  • 16,277
  • 6
  • 33
  • 45