You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
32 lines
737 B
32 lines
737 B
from dataclasses import dataclass, field
|
|
from typing import Optional
|
|
|
|
from dataclasses_json import dataclass_json, config
|
|
import json
|
|
|
|
import models.target
|
|
|
|
@dataclass_json
|
|
@dataclass
|
|
class Rectangle:
|
|
x: int
|
|
y: int
|
|
width: int
|
|
height: int
|
|
p: Optional[models.target.Point]= field(default=None, metadata=config(exclude=lambda x: x is None))
|
|
|
|
# 使用
|
|
p=models.target.Point(1,2)
|
|
rect = Rectangle(0, 0, 100, 100,None)
|
|
# 序列化
|
|
json_str=rect.to_json()
|
|
# json_str = json.dumps(rect, default=lambda obj: obj.__dict__)
|
|
print(f"序列化后={json_str}")
|
|
|
|
rect.p.x=2046
|
|
print("修改后p.x=",p.x)
|
|
|
|
new_json='{"x": 1, "y": 1, "width": 100, "height": 100, "p": {"x": 2, "y": 2}}'
|
|
nr=Rectangle.from_json(new_json)
|
|
print(nr.p)
|
|
|
|
|