JSON 转 Kotlin 数据类
将 JSON 转换为适用于 kotlinx.serialization、Gson、Moshi 或 Jackson 的 Kotlin 数据类,支持可空类型、默认值和 @SerialName 注解。
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonElement
@Serializable
data class Root(
val id: Int,
val username: String,
val email: String,
val isActive: Boolean,
val rating: Double,
val createdAt: String,
val avatarUrl: JsonElement? = null,
val tags: List<String>,
val address: Address,
val orders: List<Order>,
)
@Serializable
data class Address(
val street: String,
val city: String,
val zipCode: String,
)
@Serializable
data class Order(
val orderId: String,
val total: Double,
val items: Int,
val shipped: Boolean,
val coupon: String? = null,
)
Arrays of objects are merged: a key missing from some items becomes optional, null makes a field nullable, and identical shapes share one type. Paste several examples in an array for the most accurate types.
关于此工具
粘贴 JSON,即可为您常用的 JSON 库生成 Kotlin 数据类。可选择 kotlinx.serialization(@Serializable 和 @SerialName)、Gson(@SerializedName)、使用代码生成的 Moshi(@JsonClass 和 @Json)、Jackson(@JsonProperty),或普通数据类。属性使用 camelCase,键名不同时会添加注解,关键字用反引号转义,可选值或 null 值会变成可空类型并默认为 null。根据实际值选择 Int 或 Long,小数变成 Double,列表变成 List<T>,以 ID 为键的对象变成 Map<String, T>。嵌套对象会生成独立的数据类。您还可以在同一页面切换到 Go、Rust、C# 或 Python。
如何将 JSON 转换为 Kotlin 数据类
根据 JSON 生成 Kotlin 数据类。
- 1
粘贴 JSON
粘贴一个 JSON 对象,或一个示例数组。
- 2
选择库
选择 kotlinx.serialization、Gson、Moshi、Jackson 或普通类,并设置包名。
- 3
复制代码
复制数据类或下载 Types.kt。