Skip to content

Instantly share code, notes, and snippets.

@oboenikui
Last active November 29, 2017 15:41
Show Gist options
  • Save oboenikui/1ed1f602253ec7cafbd1cd3a07d699a3 to your computer and use it in GitHub Desktop.
Save oboenikui/1ed1f602253ec7cafbd1cd3a07d699a3 to your computer and use it in GitHub Desktop.
JSONからJackson用Kotlin data class生成
function generate(obj, className, current) {
if(!current) current = ""
var keys = Object.keys(obj)
var props = keys.map(key=>[toKotlinType(obj[key], key), key])
.map(([className, variableName]) => {
if (typeof obj[variableName] == "object" && !(obj[variableName] instanceof Array))
current = travel(obj[variableName], className, current);
else if(obj[variableName] instanceof Array)
current = travel(obj[variableName][0], toUCC(variableName), current);
return `@JsonProperty("${variableName}") val ${toLCC(variableName)}: ${className}`;
}).join(",\n ");
return current + `data class ${className}(${props})\n`;
}
function toKotlinType(obj, name) {
switch (typeof obj) {
case "string":
return "String";
case "number":
return (obj | 0) == obj ? "Int" : "Double";
case "boolean":
return "Boolean";
default:
if (obj instanceof Array) {
return `List<${toUCC(name)}>`;
}
return toUCC(name);
}
}
function toUCC(name) {
return name.split("_")
.map(flag=>flag[0].toUpperCase() + flag.substring(1))
.join("");
}
function toLCC(name) {
return name.split("_")
.map((flag, index)=> (index == 0 ? flag[0].toLowerCase() : flag[0].toUpperCase())
+ flag.substring(1))
.join("");
}
// usage: generate(JSON.parse(jsonString))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment