2017-10-28 10 views
0

私はAPIラッパーを開発していますが、空のJSONオブジェクトの逆シリアル化にはいくつか問題があります。Serdeのデフォルト実装を、nullではなく空のオブジェクトを返すように変更するにはどうすればよいですか?

APIはこのJSONオブジェクトを返します。 entitiesで空のオブジェクトをマインド:

これは messageプロパティ( 編集した)の私の同等の構造体である
{ 
    "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 
      } 
      } 
     } 
     ] 
    } 
    ] 
} 

#[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 Sを、デシリアライズすることです。

+1

JSONオブジェクトを表すのになぜVecを選択したのですか?これらの価値がどのように移転すると思いますか?実際、API **が常にオブジェクト(または配列)を返す場合、なぜ構造体に 'Option'があるのでしょうか? – Shepmaster

+0

あなたは構造体の構造が間違っています。私はコードを編集した – kper

答えて

1

私はこの問題を別の方法で解決しました。デフォルトの実装を変更する必要はありません。私はserdeのfield attributesを使用して、Noneの場合intentプロパティをスキップしました。構造体Intentsには1つのプロパティしかないので、空のオブジェクトが作成されます。

#[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, 
} 
関連する問題