GENERATE FREEZED

mail@pastecode.io avatar
unknown
python
2 years ago
5.2 kB
3
Indexable
Never
import json
import ast
import re

def fromJsonToField(input, className):
    fields = ''
    keys = input.keys()
    for key in keys:
        if type(input[key]) == type(""):

            if ('_' in str(key) or str(key).startswith('$')):
                varName = toCamel(key)
                fields += '@JsonKey(name: "{}") final String? {},\n'.format(key,
                                                                            varName)
            else:
                varName = toCamel(key)
                fields += 'final String? ' + toCamel(key) + ',\n'
        elif type(input[key]) == type(1):
            if ('_' in str(key) or str(key).startswith('$')):
                fields += '@JsonKey(name: "{}") final int? {} ,\n'.format(key,
                                                                          toCamel(key))
            else:
                fields += 'final int? ' + toCamel(key) + ',\n'
        elif type(input[key]) == type(1.0):
            if ('_' in str(key) or str(key).startswith('$')):
                fields += '@JsonKey(name: "{}") final double? {} ,\n'.format(key,
                                                                             toCamel(key))
            else:
                fields += 'final double? ' + toCamel(key) + ',\n'
        elif type(input[key]) == type(True):
            if ('_' in str(key) or str(key).startswith('$')):
                fields += '@JsonKey(name: "{}") final bool? {} ,\n'.format(key,
                                                                           toCamel(key))
            else:
                fields += 'final bool? ' + toCamel(key) + ',\n'
        elif type(input[key]) == type({}):
            if ('_' in str(key) or str(key).startswith('$')):
                fields += '@JsonKey(name: "{}") final {}? {},\n'.format(key,
                                                                        toCamel(key).title(), toCamel(key))
                fromJsonToField(input[key], toCamel(key).title())
            else:
                fields += 'final {}? {},\n'.format(
                    toCamel(key).title(), toCamel(key))
                fromJsonToField(input[key], key.title())
        elif type(input[key] == type([])):
            if ('_' in str(key) or str(key).startswith('$')):
                fields += '@JsonKey(name: "{}") final List<{}>? {},\n'.format(
                    key, toCamel(key).title(), toCamel(key))
                fromJsonToField(ast.literal_eval(
                    str(list(input[key])[0])), toCamel(key).title())
            else:
                fields += 'final List<{}>? {},\n'.format(
                    toCamel(key).title(), toCamel(key))
                fromJsonToField(ast.literal_eval(
                    str(list(input[key])[0])), toCamel(key).title())

    print(template.replace('{className}', className).replace(
        '{field}', fields.replace('"$', '"\\$')))


template = """
@freezed
class {className} with _${className} {
    const factory {className}({
       {field}
    }) = _{className};

    factory {className}.fromJson(Map<String, dynamic> json) => _${className}FromJson(json);
}
"""


def toCamel(snake_str):
    components = snake_str.split('_')
    # We capitalize the first letter of each component except the first one
    # with the 'title' method and join them together.
    if components[0] != '':
        x = components[0] + ''.join(x.title() for x in components[1:])
    else:
        x = components[1] + ''.join(x.title() for x in components[2:])
    i = 0
    while (x[i] == '$'):
        i+=1
    return x[i:]

def toSnake (camel_input):
    words = re.findall(r'[A-Z]?[a-z]+|[A-Z]{2,}(?=[A-Z][a-z]|\d|\W|$)|\d+', camel_input)
    return '_'.join(map(str.lower, words))


def getFieldName(key, type):
    if ('_' in str(key) or str(key).startswith('$')):
        return '@JsonKey(name: "{}") final {} {},\n'.format(key, key, key)
    else:
        return 'final {} {},\n'.format(key, key)

jsonString = """
{
  "notification": {
    "title": "Tạo nhóm chat",
    "body": "Nhóm chat vhhhvvvhhvv đã được tạo bởi Nguyễn Thanh Tùng. Thời gian: 09:11 01/06/2022"
  },
  "data": {
    "rocketchat_room_id": "XDob5P2To5S2BEmt4",
    "groupId": "118"
  },
  "collapse_key": "com.tcg.enduser.dev",
  "message_id": "0:1654049487363689%9e13a9ca9e13a9ca",
  "sent_time": 1654049487340,
  "from": "506562643544",
  "ttl": 2419200
}
""".replace("true", "True").replace("false", "False")


if __name__ == '__main__':

    # # print(baseJson)
    # # print(baseJson.keys())
    className = "NotificationModel"
    baseJson = ast.literal_eval(jsonString)
    print("import 'package:freezed_annotation/freezed_annotation.dart';")
    print("part '{}.freezed.dart';".format(toSnake(className)) )
    print("part '{}.g.dart';".format(toSnake(className)))

    fromJsonToField(baseJson, className)

    # print(ast.literal_eval('''{'_id': 'azS4jsNHGsB7wcpjY', 't': 'ru', 'rid': 'c4K9WSMxQWXrKJ22e', 'ts': {'$date': 1652860408908}, 'msg': 'giaptt-01-rikkeisoft.com', 'u': {'_id': '5GnTy6hDwXBZwMF4N', 'username': 'tungnt7-01-rikkeisoft.com', 'name': 'Nguyễn Thanh Tùng'}, 'groupable': False, 'unread': True, '_updatedAt': {'date': 1652860408908}}'''))