diff --git a/nonebot/utils.py b/nonebot/utils.py index e0900d12..688d0269 100644 --- a/nonebot/utils.py +++ b/nonebot/utils.py @@ -145,7 +145,7 @@ class DataclassEncoder(json.JSONEncoder): @overrides(json.JSONEncoder) def default(self, o): if dataclasses.is_dataclass(o): - return dataclasses.asdict(o) + return {f.name: getattr(o, f.name) for f in dataclasses.fields(o)} return super().default(o) diff --git a/tests/test_utils.py b/tests/test_utils.py new file mode 100644 index 00000000..282b2ab7 --- /dev/null +++ b/tests/test_utils.py @@ -0,0 +1,19 @@ +import json + +from utils import make_fake_message + + +def test_dataclass_encoder(): + from nonebot.utils import DataclassEncoder + + simple = json.dumps("123", cls=DataclassEncoder) + assert simple == '"123"' + + Message = make_fake_message() + MessageSegment = Message.get_segment_class() + ms = MessageSegment.nested(Message(MessageSegment.text("text"))) + s = json.dumps(ms, cls=DataclassEncoder) + assert ( + s + == '{"type": "node", "data": {"content": [{"type": "text", "data": {"text": "text"}}]}}' + ) diff --git a/tests/utils.py b/tests/utils.py index 0cd94be4..31939be7 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -32,6 +32,10 @@ def make_fake_message(): def image(url: str): return FakeMessageSegment("image", {"url": url}) + @staticmethod + def nested(content: "FakeMessage"): + return FakeMessageSegment("node", {"content": content}) + def is_text(self) -> bool: return self.type == "text"