About the JSON to Kotlin Data Class Generator
Kotlin data classes are the natural home for JSON payloads on Android and on the server. This generator writes one data class per object shape with val properties in camelCase, typed as String, Int, Double, Boolean, List<T> or Any? for nulls.
Property names are converted from the JSON key, so in_stock becomes inStock. Add @SerialName (kotlinx.serialization), @Json(name=) (Moshi) or @SerializedName (Gson) where the key and property differ, or configure a naming strategy in the library.
Nullability is not inferred beyond fields that are null in the sample, because a single sample cannot show optionality. Mark optional fields with ? and a default value once you know the API contract. That is worth doing before the first release: a non-null Kotlin property backed by a key the server sometimes omits throws at parse time rather than yielding a null, which is the usual way a generated model bites on Android.
Number types come from the sample in the same way, so an id that happens to fit in Int today overflows silently once it passes 2.1 billion. Widen it to Long for database keys and epoch milliseconds. Reach for JSON to Java when the models have to interoperate with Java sources, and JSON to JSON Schema when you want the payload described as a contract rather than turned into classes.
How to use
- Drop a representative JSON payload into the left pane and name the root data class.
- Copy the data classes into a Kotlin file.
- Add the serialisation annotations your library needs for renamed keys.
Common questions
- Does it add @Serializable?
- No. Annotations depend on the library; add
@Serializablefor kotlinx.serialization or@JsonClass(generateAdapter = true)for Moshi. - Why Int and Double instead of Long and Float?
- They match the most common defaults. Change to Long for ids that may exceed 2 billion and Float only when memory matters.
- Are the properties val or var?
- val, since parsed data is usually treated as immutable. Change to var if you mutate models.