Kotlin:数据类的JsonProperty.Access.READ_ONLY

时间:2017-05-22 09:52:49

标签: jackson kotlin jackson-databind

我想存档这样的内容:

CreateWICTextureFromFile

不幸的是,这导致以下异常:

data class Task(
  @JsonProperty("id", access = READ_ONLY)
  val id: String?

  ...
  <other params>
  ...
)

这个有效:

com.fasterxml.jackson.databind.JsonMappingException:
Argument #0 of constructor [constructor for Task, annotations: [null]] 
has no property name annotation;
must have name when multiple-parameter constructor annotated as Creator
at [Source: {"id":"AT-5", ...}; line: 1, column: 1]

    at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:305)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:268)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCacheValueDeserializer(DeserializerCache.java:244)
    at com.fasterxml.jackson.databind.deser.DeserializerCache.findValueDeserializer(DeserializerCache.java:142)
    at com.fasterxml.jackson.databind.DeserializationContext.findRootValueDeserializer(DeserializationContext.java:476)
    at com.fasterxml.jackson.databind.ObjectMapper._findRootDeserializer(ObjectMapper.java:3899)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3794)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2842)

我试过data class Task( @JsonProperty("id") val id: String? ) 无效。

如何在Kotlin中使用此注释? 我使用dropwizard 1.1.0,Jackson 2.8.6

1 个答案:

答案 0 :(得分:2)

您应该使用Jackson-Kotlin模块,然后您不需要为每个参数设置JsonParameter,因为模块将根据Kotlin编译器在类中存储的元数据推断其他参数名称。

该模块位于Github FasterXML/jackson-module-kotlin

请务必按照说明注册模块,在您自己的版本中包含kotlin-reflect依赖项,并使用帮助函数来简化您的Kotlin代码。