(Moshi in kotlin) @Json vs @field:Json

浪子不回头ぞ 提交于 2019-12-07 13:15:26

问题


Serialization does not happen properly when I use @Json in the fields but it started working after changing to @field:Json.

I came through this change after reading some bug thread and I think this is specific to kotlin. I would like to know what difference does @field:Json bring and is it really specific to kotlin?


回答1:


Whatever you put between @ and : in your annotation specifies the exact target for your Annotation.

When using Kotlin with JVM there is a substantial number of things generated, therefore your Annotation could be put in many places. If you don't specify a target you're letting the Kotlin compiler choose where the Annotation should be put. When you specify the target -> you're in charge.

To better see the difference you should inspect the decompiled Java code of the Kotlin Bytecode in IntelliJ/Android Studio.


Example kotlin code:

class Example {

    @ExampleAnnotation
    val a: String = TODO()

    @get:ExampleAnnotation
    val b: String = TODO()

    @field:ExampleAnnotation
    val c: String = TODO()
}

Decompiled Java code:

public final class Example {
   @NotNull
   private final String a;
   @NotNull
   private final String b;
   @ExampleAnnotation
   @NotNull
   private final String c;

   /** @deprecated */
   // $FF: synthetic method
   @ExampleAnnotation
   public static void a$annotations() {
   }

   @NotNull
   public final String getA() {
      return this.a;
   }

   @ExampleAnnotation
   @NotNull
   public final String getB() {
      return this.b;
   }

   @NotNull
   public final String getC() {
      return this.c;
   }

   public Example() {
      boolean var1 = false;
      throw (Throwable)(new NotImplementedError((String)null, 1, (DefaultConstructorMarker)null));
   }
}

For more info go to Kotlin docs.



来源:https://stackoverflow.com/questions/56976656/moshi-in-kotlin-json-vs-fieldjson

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!