Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson @JsonIgnoreProperties multiple fields with Kotlin

Tags:

kotlin

jackson

I'm having trouble using @JsonIgnoreProperties with kotlin. I need to ignore more than one property, and I see many tutorial/SO questions where, with java, usually you do something like that:

@JsonIgnoreProperties({ "p0", "p1", "p2" })
class Example(){...}

So in kotlin it would be:

@JsonIgnoreProperties(value = arrayOf( "p0", "p1", "p2" ))
class Example(){...}

The value field of the JsonIgnoreProperties interface should accept array, since it's declared in this way:

public String[] value() default { };

But the compiler complains and want a string, not an array. I can't even duplicate the annotation, so how should I do to ignore more than one field?

EDIT: Seems like it's a kotlin missing feature, implemented since 1.2 beta. it will be possible to use value = ["p0", "p1", "p2"] for annotations. Before 1.2 beta it's possible to use @JsonIgnoreProperties("p0", "p1", "p2"), no way to prepend the array with value =

like image 849
Dario Coletto Avatar asked Sep 12 '25 00:09

Dario Coletto


1 Answers

You can use the spread operator here, which is what the Java to Kotlin converter does with your example code, and also what Android Studio suggests as a quick fix:

@JsonIgnoreProperties(value = *arrayOf( "p0", "p1", "p2" ))
class Example { ... }

The quick fix intention action

This works because array types in annotation parameters get converted to varargs in Kotlin, so you could just do this if you're not using an Array from somewhere else:

@JsonIgnoreProperties("p0", "p1", "p2")
class Example
like image 100
zsmb13 Avatar answered Sep 13 '25 15:09

zsmb13