(kotlin 中的 Moshi)@Json vs @field:Json

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

当我在字段中使用 @Json 时,序列化没有正确发生,但在更改为 @field:[=20 后它开始工作=].

我在阅读了一些错误讨论帖后完成了这个更改,我认为这是 kotlin 特有的。我想知道 @field:Json 带来什么区别,它真的是 kotlin 特有的吗?

无论您在注释中的 @: 之间输入什么,都会为您的注释指定确切的 target

将 Kotlin 与 JVM 结合使用时会生成大量内容,因此您的 Annotation 可能会放在很多地方。如果您不指定 target ,您将让 Kotlin 编译器选择注释的放置位置。当您指定 target -> 您负责。

为了更好地了解差异,您应该在 IntelliJ/Android Studio 中检查 Kotlin 字节码的反编译 Java 代码。


Kotlin 代码示例:

class Example {

    @ExampleAnnotation
    val a: String = TODO()

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

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

反编译Java代码:

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));
   }
}

有关详细信息,请转到 Kotlin docs