如何更改Serde的默认实现以返回一个空对象而不是null? [英] How do I change Serde's default implementation to return an empty object instead of null?
问题描述
我正在开发API包装器,并且在对空JSON对象进行反序列化时遇到了一些麻烦.
I'm developing an API wrapper and I'm having some troubles with the deserialization of an empty JSON object.
API返回此JSON对象.注意entities
处的空对象:
The API returns this JSON object. Mind the empty object at 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
属性(已编辑)的等效结构:
This is my equivalent struct of the message
property (edited):
#[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,
}
Serde的默认设置是使用::serde_json::Value::Null
反序列化None
的Option
.
Serde's default is to deserialize Option
s, which are None
, with ::serde_json::Value::Null
.
推荐答案
我以不同方式解决了此问题,无需更改默认实现.当Option为None
时,我使用了Serde的字段属性来跳过intent
属性.由于struct Intents
中只有一个属性,因此将创建一个空对象.
I solved this problem differently with no need to change the default implementation. I used serde's field attributes to skip the intent
property when the Option is None
. Because there is only one property in the struct Intents
, this will create an empty object.
#[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,
}
这篇关于如何更改Serde的默认实现以返回一个空对象而不是null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!