调换序列化顺序

This commit is contained in:
zqm
2026-04-07 17:22:49 +08:00
parent faa0b3cb5e
commit a61f65b905
2 changed files with 21 additions and 1 deletions

View File

@@ -637,7 +637,7 @@ impl WebSocketClient {
/// Send a text message
pub async fn send(&self, msg_type: &str, data: Value) -> Result<(), WebSocketError> {
let message = WebSocketMessage::new(msg_type, data);
let json = serde_json::to_string(&message)?;
let json = message.to_json_string()?;
self.send_raw_text(json).await
}

View File

@@ -45,6 +45,26 @@ impl WebSocketMessage {
let data = serde_json::to_value(data)?;
Ok(Self::new(msg_type, data))
}
/// Serialize to JSON string with Type field first (required by MasterSuite protocol)
/// Note: serde's default serialization order follows field definition order,
/// but this method guarantees Type comes first regardless of any future changes
pub fn to_json_string(&self) -> Result<String, serde_json::Error> {
let mut map = serde_json::Map::new();
// Type is always first
map.insert("Type".to_string(), serde_json::Value::String(self.msg_type.clone()));
// Data field
map.insert("Data".to_string(), self.data.clone());
// MessageId (optional, skip if None)
if let Some(ref id) = self.id {
map.insert("MessageId".to_string(), serde_json::Value::String(id.clone()));
}
serde_json::to_string(&map)
}
}
/// Client type enumeration