我有一个 Java 服务器应用程序,它使用 Jackson 使用反射 API 对 DTO 进行一般序列化。例如对于这个 DTO 接口(interface):
package com.acme.library;
public interface Book {
com.acme.library.Author getAuthor();
String getTitle();
}
从这个接口(interface)的 POJO 实现中,Jackson 一般会序列化以下实体:
{
"author": { "name": "F. Scott Fitzgerald"},
"title": "The Great Gatsby"
}
此有效负载将使用我的 TypeScript 应用程序中的 HTTP GET 接收,该应用程序基于 AngularJS:
$http.get("http://localhost/books/0743273567")
.success((book: Book) => { ... });
为了能够使用 TypeScript 的强类型特性,我发现自己手动编写了以下 typescript 接口(interface):
module com.acme.library {
export interface Book {
author: com.acme.library.Author;
title: String;
}
}
因此,我必须维护同一个界面的两个副本——这充其量是很麻烦的。这变得特别讨厌,因为我希望在两个接口(interface)上都有相同的 javadoc/jsdoc 注释,这涉及到大量的复制和粘贴。
我想找到一种机制来自动化这个过程。
Java 是我的主要开发语言。因此,我想找到一些能够从 Java 接口(interface)声明(通过反射 API?)转换为相关 TypeScript 接口(interface)的工具。
我在这个领域发现的唯一工具是 NPM 包 ts-java
。但是,这对于我的用例来说太重了。它将对象层次结构中的方法添加到每个接口(interface),例如hashCode()
、wait()
、getClass()
等
最佳答案
您可以使用 typescript-generator正如拉尔斯隆所说。它从 Java JSON 类生成 TypeScript 接口(interface)。一些您可能会觉得有用的功能:
- Maven 和 Gradle 插件(也可以直接从 Java 调用)
- jackson 1 和 jackson 2
- 集合、枚举、继承、泛型
- Javadoc 注释到 JSDoc 注释
- 详细的文档(README、Wiki、Maven 插件)
- 在 Maven 中央仓库中发布
这里是如何在 Maven 中使用它的示例:
<plugin>
<groupId>cz.habarta.typescript-generator</groupId>
<artifactId>typescript-generator-maven-plugin</artifactId>
<version>1.25.322</version>
<executions>
<execution>
<id>generate</id>
<goals>
<goal>generate</goal>
</goals>
<phase>process-classes</phase>
<configuration>
<jsonLibrary>jackson2</jsonLibrary>
<classes>
<class>com.acme.library.Book</class>
</classes>
<outputFile>target/rest.d.ts</outputFile>
<outputKind>module</outputKind>
</configuration>
</execution>
</executions>
</plugin>
编辑:使用 mvn process-classes
运行它或使用后期阶段,如 mvn install
.
也可以拉<configuration>
元素向上运行两级 mvn typescript-generator:generate
.
编辑:我是 typescript-generator 的作者。
关于java - 从 Java 接口(interface)生成 Typescript 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32451966/