그래서 다음과 같은 JSON이 있습니다.
{
"name": "customer",
"properties": [
{
"name": "id",
"type": "int",
"value": 32
},
{
"name": "name",
"type": "string",
"value": "John"
}
]
}
현재 나는이 구조체 세트로 deserialize하고 있습니다.
#[derive(Serialize, Deserialize, Debug)]
struct Customer {
name: String,
properties: Vec<Property>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(tag = "name", content = "value")]
enum Property {
#[serde(rename = "id")]
Id(i32),
#[serde(rename = "name")]
Name(String),
}
그러나 속성에 액세스 할 때마다 열거 형을 통한 일치를 처리하지 않으려면 다음과 같은 구조체로 역 직렬화하고 싶습니다.
struct Customer {
name: String,
properties: Properties,
}
struct Properties {
id: i32, // will be 32 as in the object containing the name "id".
name: String, // will be John as in the object containing the name "name".
}
이것이 serde
도서관이 어떤 식 으로든 허용하는 것입니까? 그렇다면 그것을 달성하는 방법에 대한 예를 제공 할 수 있습니까?
실제 json 구조를 엉망으로 만들 수 없으므로 필요한 솔루션에 관심이 없습니다.
edkeveked의 답변 덕분 에 내 요구 사항에 맞는 솔루션을 찾을 수있었습니다.
기본적으로 Deserializer를 재정렬하여 전체 속성 배열을 반복하고 그 안의 모든 개체를 Enum 변형과 일치 시키려고했습니다. 나는 미래에 새 속성을 쉽게 매핑 할 수 있고 유형별로 더 유연하게 느껴지기 때문에 이것을 좋아합니다.
어쨌든, 여기에 대한 코드가 있습니다.
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
use serde::de::{Deserializer, SeqAccess, Visitor};
use std::fmt;
#[derive(Serialize, Deserialize, Debug)]
struct Customer {
name: String,
#[serde(deserialize_with = "parse_property")]
properties: CustomerProps,
}
#[derive(Default, Serialize, Deserialize, Debug)]
struct CustomerProps {
id: i32,
name: String,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(tag = "name", content = "value")]
enum Property {
#[serde(rename = "id")]
Id(i32),
#[serde(rename = "name")]
Name(String),
}
fn parse_property<'de, D>(deserializer: D) -> Result<CustomerProps, D::Error>
where
D: Deserializer<'de>,
{
struct PropertyParser;
impl<'de> Visitor<'de> for PropertyParser {
type Value = CustomerProps;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("[u64, f32, usize]")
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
let mut prop = CustomerProps {
..Default::default()
};
while let Some(tmp) = seq.next_element::<Property>()? {
match tmp {
Property::Id(id) => prop.id = id,
Property::Name(name) => prop.name = name,
}
}
Ok(prop)
}
}
deserializer.deserialize_any(PropertyParser {})
}
fn main() {
let data = r#"{
"name": "customer",
"properties": [
{
"name": "id",
"type": "int",
"value": 32
},
{
"name": "name",
"type": "string",
"value": "John"
}
]
}"#;
let p: Customer = serde_json::from_str(data).unwrap();
println!("Please call {} at the number {} {}", p.name, p.properties.id, p.properties.name);
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다