JSON 转 Java 类工具
从 JSON 生成带 getter 和 setter 的 Java 类,并附带基于 Jackson 的 Converter。
从 JSON 生成 Java POJO
在 Java 中映射 JSON,通常需要为每个对象编写一个 POJO,包含私有字段、getter、setter 和注解。本工具会根据样例自动生成:每个对象生成一个类,访问器上带有 Jackson 的 @JsonProperty 注解;嵌套对象生成独立的类;数组生成类型化数组;整数映射为 long。另外还会生成一个提供 fromJsonString 和 toJsonString 方法的 Converter 类,封装了 Jackson ObjectMapper 的配置,并包含日期和时间解析的辅助方法。
使用方法
- 粘贴一段 JSON 样例,例如你的 Spring 或 Android 应用所使用的 REST 响应。
- 输入根类名称,例如 Customer。
- 在 Maven 或 Gradle 构建中添加 jackson-databind,把每个类移到包中各自的 .java 文件里,然后调用 Converter.fromJsonString(json)。
常见问题
- 为什么输出这么长?
- Java 需要显式声明字段、getter 和 setter,生成的 Converter 还包含面向 java.time API 的日期时间辅助方法。如果只需要模型,复制数据类并使用你现有的 ObjectMapper 即可。
- 可以改用 Java record 或 Lombok 吗?
- 为了获得最大的兼容性,生成器输出的是传统类。复制后你可以将它们改写为 record(Java 16+),或加上 Lombok 的 @Data 注解;Jackson 两者都支持。
- 可以在 Spring Boot 中使用吗?
- 可以。Spring Boot 默认使用 Jackson,因此这些带注解的类可以直接用作 @RequestBody 或响应类型,无需 Converter 类。
示例:JSON 转 Java
输入 JSON
{
"customerId": 501,
"fullName": "Grace Hopper",
"vip": true,
"addresses": [{ "city": "Arlington", "zip": "22201" }]
}生成的 Java 代码(Customer)
// Converter.java
// To use this code, add the following Maven dependency to your project:
//
//
// com.fasterxml.jackson.core : jackson-databind : 2.9.0
// com.fasterxml.jackson.datatype : jackson-datatype-jsr310 : 2.9.0
//
// Import this package:
//
// import io.quicktype.Converter;
//
// Then you can deserialize a JSON string with
//
// Customer data = Converter.fromJsonString(jsonString);
package io.quicktype;
import java.io.IOException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.util.*;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
public class Converter {
// Date-time helpers
private static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder()
.appendOptional(DateTimeFormatter.ISO_DATE_TIME)
.appendOptional(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
.appendOptional(DateTimeFormatter.ISO_INSTANT)
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SX"))
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssX"))
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
.toFormatter()
.withZone(ZoneOffset.UTC);
public static OffsetDateTime parseDateTimeString(String str) {
return ZonedDateTime.from(Converter.DATE_TIME_FORMATTER.parse(str)).toOffsetDateTime();
}
private static final DateTimeFormatter TIME_FORMATTER = new DateTimeFormatterBuilder()
.appendOptional(DateTimeFormatter.ISO_TIME)
.appendOptional(DateTimeFormatter.ISO_OFFSET_TIME)
.parseDefaulting(ChronoField.YEAR, 2020)
.parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
.parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
.toFormatter()
.withZone(ZoneOffset.UTC);
public static OffsetTime parseTimeString(String str) {
return ZonedDateTime.from(Converter.TIME_FORMATTER.parse(str)).toOffsetDateTime().toOffsetTime();
}
// Serialize/deserialize helpers
public static Customer fromJsonString(String json) throws IOException {
return getObjectReader().readValue(json);
}
public static String toJsonString(Customer obj) throws JsonProcessingException {
return getObjectWriter().writeValueAsString(obj);
}
private static ObjectReader reader;
private static ObjectWriter writer;
private static void instantiateMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.findAndRegisterModules();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
SimpleModule module = new SimpleModule();
module.addDeserializer(OffsetDateTime.class, new JsonDeserializer<OffsetDateTime>() {
@Override
public OffsetDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
String value = jsonParser.getText();
return Converter.parseDateTimeString(value);
}
});
mapper.registerModule(module);
reader = mapper.readerFor(Customer.class);
writer = mapper.writerFor(Customer.class);
}
private static ObjectReader getObjectReader() {
if (reader == null) instantiateMapper();
return reader;
}
private static ObjectWriter getObjectWriter() {
if (writer == null) instantiateMapper();
return writer;
}
}
// Customer.java
package io.quicktype;
import com.fasterxml.jackson.annotation.*;
public class Customer {
private long customerID;
private String fullName;
private boolean vip;
private Address[] addresses;
@JsonProperty("customerId")
public long getCustomerID() { return customerID; }
@JsonProperty("customerId")
public void setCustomerID(long value) { this.customerID = value; }
@JsonProperty("fullName")
public String getFullName() { return fullName; }
@JsonProperty("fullName")
public void setFullName(String value) { this.fullName = value; }
@JsonProperty("vip")
public boolean getVip() { return vip; }
@JsonProperty("vip")
public void setVip(boolean value) { this.vip = value; }
@JsonProperty("addresses")
public Address[] getAddresses() { return addresses; }
@JsonProperty("addresses")
public void setAddresses(Address[] value) { this.addresses = value; }
}
// Address.java
package io.quicktype;
import com.fasterxml.jackson.annotation.*;
public class Address {
private String city;
private String zip;
@JsonProperty("city")
public String getCity() { return city; }
@JsonProperty("city")
public void setCity(String value) { this.city = value; }
@JsonProperty("zip")
public String getZip() { return zip; }
@JsonProperty("zip")
public void setZip(String value) { this.zip = value; }
}