다음 JSON 스 니펫을 Vec
구조체 로 역 직렬화하려고합니다 Shape
.
use serde::{Deserialize, Serialize};
use serde_json::{Result, Value};
#[derive(Debug, Serialize, Deserialize)]
struct Shape { // this struct is not working, for display purpose only
shape_type: String,
d0: f64,
d1: f64,
d2: f64, //optional, like the case of "dot"
d3: f64, //optional, like the case of "circle"
}
let json = r#"
{[
["line", 1.0, 1.0, 2.0, 2.0],
["circle", 3.0, 3.0, 1.0],
["dot", 4.0, 4.0]
]}"#;
let data: Vec<Shape> = match serde_json::from_str(json)?;
분명히, 각 유형은 그것을 설명하기 위해 다른 숫자가 Shape
필요 합니다. 위와 같이 JSON 데이터를 역 직렬화하는 구조체를 어떻게 정의해야 합니까?String
f64
Shape
당신은 내가 강력하게 추천하는 JSON 형식으로 제어가 가정 Shape
으로 유형을 enum
여러 모양을 나타낼 수있는 자동 구현 serde의 파생 매크로를 사용 Serialize
하고 Deserialize
위해를 Shape
. 예:
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct Point {
x: f64,
y: f64,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type")]
enum Shape {
Dot { position: Point },
Line { start: Point, end: Point },
Circle { center: Point, radius: f64 },
}
fn main() {
let shapes = vec![
Shape::Dot {
position: Point { x: 3.0, y: 4.0 },
},
Shape::Line {
start: Point { x: -2.0, y: 1.0 },
end: Point { x: 5.0, y: -3.0 },
},
Shape::Circle {
center: Point { x: 0.0, y: 0.0 },
radius: 7.0,
},
];
let serialized = serde_json::to_string(&shapes).unwrap();
println!("serialized = {}", serialized);
let deserialized: Vec<Shape> = serde_json::from_str(&serialized).unwrap();
println!("deserialized = {:?}", deserialized);
}
JSON 형식을 절대 변경할 수 없다면 serde가 도움이되지 않습니다. 모양을 이기종 문자열 및 부동 배열로 직렬화하는 것은 매우 기괴한 선택입니다. 수동으로 다음 직접 (또는 도움이 당신에게 이상 사용에서 일부 파서 상자를) 구문 분석해야 디시리얼라이저 특성을 구현하는 수동 그것으로 바꿀 수 있도록 Shape
.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다