-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathkotlin-named-type.mustache
65 lines (59 loc) · 2.05 KB
/
kotlin-named-type.mustache
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
{{#custom}}
data class {{typeName}}(
{{#members}}
@JvmField val {{name}}: {{type}}{{#defaultValue}} = {{defaultValue}}{{/defaultValue}},
{{/members}}
{{#staticMembers}}
@JvmField val {{name}}: {{type}} = {{{value}}},
{{/staticMembers}}
)
{{/custom}}
{{#enum}}
{{#isNumberType}}
enum class {{typeName}}(val value: Int) {
{{#members}}
{{key}}({{{value}}}){{^last}},{{/last}}{{#last}};{{/last}}
{{/members}}
companion object {
fun find(value: Int) = values().find { it.value == value }
}
}
class {{typeName}}TypeAdapter : JsonSerializer<{{typeName}}>, JsonDeserializer<{{typeName}}> {
override fun serialize(obj: {{typeName}}, type: Type, context: JsonSerializationContext): JsonElement {
return JsonPrimitive(obj.value)
}
override fun deserialize(json: JsonElement, type: Type, context: JsonDeserializationContext): {{typeName}}? {
return {{typeName}}.find(json.asInt)
}
}
{{/isNumberType}}
{{#isStringType}}
enum class {{typeName}} {
{{#members}}
@SerializedName({{{value}}}) {{key}}{{^last}},{{/last}}
{{/members}}
}
{{/isStringType}}
{{/enum}}
{{#unionType}}
sealed class {{unionTypeName}}(val value: Any) {
{{#members}}
data class {{capitalizeName}}Value(val value: {{{type}}}) : {{unionTypeName}}()
{{/members}}
}
class {{unionTypeName}}Adapter : JsonSerializer<{{unionTypeName}}>, JsonDeserializer<{{unionTypeName}}> {
override fun serialize(src: {{unionTypeName}}, typeOfSrc: Type, context: JsonSerializationContext): JsonElement {
return context.serialize(src.value)
}
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): {{unionTypeName}} {
{{#members}}
try {
return {{unionTypeName}}.{{capitalizeName}}Value(context.deserialize(json, {{type}}::class.java))
} catch (e: Exception) {
// Ignore the exception and try the next type
}
{{/members}}
throw IllegalArgumentException("Unexpected JSON type: ${json.javaClass}")
}
}
{{/unionType}}