Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
JSON形式のAPIレスポンスからJavaクラスを生成(書き殴り)
import json
class JavaClass:
def __init__(self, name):
self.name = name
self.fields = dict()
def add_field(self, java_type, name):
self.fields[name] = java_type
def __str__(self):
output = 'public class ' + self.name + ' {\n'
for idx, field_name in enumerate(self.fields):
java_type = self.fields[field_name]
output += ' @SerializedName("' + field_name + '")\n'
output += ' ' + java_type + ' ' + to_camel(field_name) + ';\n'
if idx != len(self.fields) - 1:
output += '\n'
output += '}'
return output
def to_camel(snake_str):
words = snake_str.split('_')
return words[0] + ''.join(word.title() for word in words[1:])
def gen_java_classes(class_name, classes, source):
java_class = JavaClass(class_name)
for idx, field_name in enumerate(source):
field_value = source.get(field_name)
python_type = type(field_value)
if python_type == str:
java_type = 'String'
elif python_type == int:
java_type = 'int'
elif python_type == bool:
java_type = 'boolean'
elif python_type == dict:
java_type = field_name.title()
gen_java_classes(field_name.title(), classes, field_value)
elif python_type == list:
java_type = 'List<' + field_name.title() + '>'
field_value = field_value[0]
gen_java_classes(field_name.title(), classes, field_value)
else:
java_type = 'Object'
java_class.add_field(java_type, field_name)
classes.append(java_class)
return classes
print('Enter outer class name')
outer_class_name = input()
print('Enter Json')
input_lines = list()
while True:
input_line = input()
if input_line:
input_lines.append(input_line)
else:
json_str = '\n'.join(input_lines)
break
json_dict = json.loads(json_str)
java_classes = gen_java_classes(outer_class_name, [], json_dict)
for item in java_classes:
print(str(item) + '\n')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.