Python类方法写入JSON文件时报Rectangle对象不可序列化错误
错误根因
- JSON 模块默认仅支持序列化字典、列表、字符串、数字等Python内置基础类型,无法直接序列化自定义的
Rectangle类实例 - 现有代码逻辑存在三处方法定义/调用错误:
Base.to_json_string设计接收字典列表入参,但实际传入了Rectangle实例列表,未做实例到属性字典的转换to_json_string方法未添加@staticmethod装饰器,作为普通类内方法调用时会触发参数匹配错误save_to_file中错误使用cls(Base.to_json_string(list_objs))写法,该写法意图是用JSON字符串实例化当前类,和写入文件的需求完全不符
修复方案
- 给
Rectangle类新增实例转属性字典的方法
class Rectangle(Base): # 原有__init__等逻辑保留,新增以下方法 def to_dictionary(self): return { "id": self.id, "width": self.width, "height": self.height, "x": self.x, "y": self.y }
- 修改
Base类的方法定义与调用逻辑
import json class Base: @staticmethod def to_json_string(list_dictionaries): if not list_dictionaries: return "[]" return json.dumps(list_dictionaries) @classmethod def save_to_file(cls, list_objs): filename = f"{cls.__name__}.json" # 先将所有实例转换为字典列表 dict_list = [obj.to_dictionary() for obj in list_objs] if list_objs else [] # 生成JSON字符串后直接写入文件 with open(filename, "w", encoding="utf-8") as f: f.write(cls.to_json_string(dict_list))
修改后运行测试代码即可输出预期的JSON内容。
内容的提问来源于stack exchange,提问作者seahorse-code
相关产品推荐
相关产品推荐

