Как изменить реализацию по умолчанию в Serde, чтобы она возвращала пустой объект вместо null?
Я разрабатываю оболочку API и у меня возникают проблемы с десериализацией пустого объекта JSON.
API возвращает этот объект JSON. Следите за пустым объектом в entities
:
{
"object": "page",
"entry": [
{
"id": "1158266974317788",
"messaging": [
{
"sender": {
"id": "some_id"
},
"recipient": {
"id": "some_id"
},
"message": {
"mid": "mid.$cAARHhbMo8SBllWARvlfZBrJc3wnP",
"seq": 5728,
"text": "test",
"nlp": {
"entities": {} // <-- here
}
}
}
]
}
]
}
Это моя эквивалентная структура message
свойство (отредактировано):
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct TextMessage {
pub mid: String,
pub seq: u64,
pub text: String,
pub nlp: NLP,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct NLP {
pub entities: Intents,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Intents {
intent: Option<Vec<Intent>>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Intent {
confidence: f64,
value: String,
}
По умолчанию серде десериализации Option
с, которые None
, с ::serde_json::Value::Null
,
1 ответ
Решение
Я решил эту проблему по-другому без необходимости менять реализацию по умолчанию. Я использовал атрибуты полей serde, чтобы пропустить intent
свойство, когда опция None
, Потому что в структуре есть только одно свойство Intents
, это создаст пустой объект.
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct TextMessage {
pub mid: String,
pub seq: u64,
pub text: String,
pub nlp: NLP,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct NLP {
pub entities: Intents,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Intents {
#[serde(skip_serializing_if="Option::is_none")]
intent: Option<Vec<Intent>>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Intent {
confidence: f64,
value: String,
}