-1
  • I have a kotlin data class, having a parameterized constructor, and a method which derives its output based on a property.
  • I have annotated this method with @JsonProperty so that its derived output can also be serialized to output JSON, as that was a requirement to me.
  • Now the issue arises when I try to deserialize this JSON, and it doesn't find any field for the derivedProp

Cannot construct instance of MyDataClass, problem: Should never call set() on setterless property ('derivedProp')

@JsonIgnoreProperties(ignoreUnknown = false)
data class MyDataClass(
   val boolProp: Boolean = true,
   val dataProp: DataProp = DataProp(),
   val mainProp: String? = null
) : Serializable {

   @JsonProperty
   @Suppress("unused")
   fun derivedProp(): List =
      someLogicOnMainProp(mainProp)

}
Vivek Gupta
  • 2,534
  • 3
  • 15
  • 28
  • 1
    `val` defines immutable variables, so there is not setter for a val. Using `var` instead of `val` will fix the issue –  Dec 17 '18 at 10:15
  • issue is not for the 3 properties declared as val, it is for the forth one, which is created at the time of serialization due to the method derivedProp() – Vivek Gupta Dec 17 '18 at 10:16
  • Possible duplicate of [Only using @JsonIgnore during serialization, but not deserialization](https://stackoverflow.com/questions/12505141/only-using-jsonignore-during-serialization-but-not-deserialization) – talex Dec 17 '18 at 10:23
  • could you please explain, how ? – Vivek Gupta Dec 17 '18 at 11:35

2 Answers2

2

I solved this problem using the below property on @JsonProperty annotation:

@JsonProperty(access = Access.WRITE_ONLY)
Vivek Gupta
  • 2,534
  • 3
  • 15
  • 28
0

If you use a property instead of a function, you can still define a setter and just ignore it, when it's called. Not the prettiest solution, but should do the trick:

@get:JsonProperty
var derivedProp: List<Any>
    get() = someLogicOnMainProp(mainProp)
    set(value) { /* do nothing */ }
Patric
  • 1,489
  • 13
  • 28