我需要进一步回答有关在嵌套结构中使用@dataclass
进行JSON序列化的问题,该问题来自Make the Python json encoder support Python's new dataclasses。
请考虑以下情况:
import json
from attr import dataclass
from dataclasses_json import dataclass_json
@dataclass
@dataclass_json
class Prod:
id: int
name: str
price: float
prods = [Prod(1,'A',25.3),Prod(2,'B',79.95)]
pjson = json.dumps(prods)
这给我们带来了:
TypeError: Object of type Prod is not JSON serializable
请注意,上述内容包含其中一个答案https://dev59.com/qlUK5IYBdhLWcg3wySbB#59688140。它通过dataclass_json
装饰器声称支持嵌套情况。显然,实际上并不起作用。我还尝试了另一个答案https://dev59.com/qlUK5IYBdhLWcg3wySbB#51286749:
class EnhancedJSONEncoder(json.JSONEncoder):
def default(s, o):
if dataclasses.is_dataclass(o):
return dataclasses.asdict(o)
return super().default(o)
我为此创建了一个帮助方法:
def jdump(s,foo):
return json.dumps(foo, cls=s.c.EnhancedJSONEncoder)
但使用那种方法也没有影响(错误)结果。还有其他提示吗?