zoukankan      html  css  js  c++  java
  • python json转对象 指定字段名称

    # -*- coding:utf-8 -*-
    import importlib
    import os
    
    print(os.path.realpath(__file__))
    print(os.path.abspath(__file__))
    
    car_json_body = {
        "carId": 1,
        "company": {
            "name": "c_1",
        }
    }
    
    
    class Car(object):
        def __init__(self):
            self._car_id = None
            self._company = None
    
        @property
        def carId(self):
            return self._car_id
    
        @carId.setter
        def carId(self, car_id):
            self._car_id = car_id
    
        @property
        def company(self):
            return self._company
    
        @company.setter
        def company(self, company):
            if isinstance(company, Company):
                self.company = company
                return
    
            self._company = parse_json_to_object(company, "test_json.Company")
    
    
    class Company(object):
        def __init__(self):
            self._name = None
    
        @property
        def name(self):
            return self._name
    
        @name.setter
        def name(self, name):
            self._name = name
    
    
    def parse_json_to_object(obj_json, class_full_path=None):
        """ 根据给定的json字典和待转换的类的全路径,得到反序列化后的对象 """
        print("data json:%s." % obj_json)
        print("class full path:%s." % class_full_path)
    
        if obj_json is None:
            print("Have no obj json.")
            return None
    
        if class_full_path is None:
            return obj_json
        else:
            try:
                # 获取模块路径
                module_path = ".".join(class_full_path.split(".")[0:-1])
                # 获取类名称
                class_name = class_full_path.split(".")[-1]
                # 通过模块名加载模块
                imported_module_obj = importlib.import_module(module_path)
                # 判断是否有class_name所代表的属性
                if hasattr(imported_module_obj, class_name):
                    # 获取模块中属性
                    temp_obj_class = getattr(imported_module_obj, class_name)
                    # 实例化对象
                    temp_obj = temp_obj_class()
                    for key in obj_json:
                        temp_obj.__setattr__(key, obj_json[key])
                    return temp_obj
                else:
                    print("Can not find class:%s in module:%s." % (class_name, module_path))
                    return None
    
            except Exception as err:
                print("Error:", err)
                return None
    
    
    c = parse_json_to_object(car_json_body, "test_json.Car")
    print(c.__dict__)
    

      采用 

    @property 和 python中的反射机制实现反解析json
  • 相关阅读:
    python dataframe根据变量类型选取变量
    史上最简单的Xgboost安装教程 for Python3.7 on Win10!亲测有效!
    Python三种基础数据类型:列表list,元祖tuple和字典dict
    Time 模块
    第二周 3(实战:中国大学排名定向爬虫)
    第二周 2(信息标记与提取)
    第二周 1(beautiful soup库)
    第一周 2(requests库实战)
    第一周 1 (requests库)
    pd.concat()
  • 原文地址:https://www.cnblogs.com/dasheng-maritime/p/13050578.html
Copyright © 2011-2022 走看看