2017-10-28 71 views
0

我正在開發一個API包裝器,並且對空的JSON對象的反序列化有一些麻煩。如何更改Serde的默認實現以返回空對象而不是null?

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, 
} 

SERDE的默認值是反序列化Option s,這是None,與::serde_json::Value::Null

+1

你爲什麼選擇'Vec'來表示一個JSON對象?你如何期待這些價值觀轉移?事實上,如果API **總是**返回一個對象(或數組,無論),爲什麼你甚至在你的結構中有一個'Option'? – Shepmaster

+0

是的,你是對的結構的結構是錯的。我編輯了代碼 – kper

回答

1

我解決了這個問題,不需要更改默認實現。當選項爲None時,我使用serde的field attributes跳過intent屬性。因爲struct 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, 
} 
相關問題