Skip to main content

openai_core/
json_payload.rs

1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3use std::fmt;
4use std::ops::Deref;
5
6/// 通用的原始 JSON 载荷包装器。
7#[derive(Clone, Serialize, Deserialize, Default, PartialEq)]
8#[serde(transparent)]
9pub struct JsonPayload(Value);
10
11impl fmt::Debug for JsonPayload {
12    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
13        self.0.fmt(f)
14    }
15}
16
17impl JsonPayload {
18    /// 返回未经解释的原始 JSON 值。
19    pub fn as_raw(&self) -> &Value {
20        &self.0
21    }
22
23    /// 消费包装器并返回原始 JSON 值。
24    pub fn into_raw(self) -> Value {
25        self.0
26    }
27
28    /// 返回载荷中的 `type` 字段,若存在且为字符串。
29    pub fn kind(&self) -> Option<&str> {
30        self.0.get("type").and_then(Value::as_str)
31    }
32
33    /// 返回载荷中指定 key 的原始 JSON 值。
34    pub fn get(&self, key: &str) -> Option<&Value> {
35        self.0.get(key)
36    }
37}
38
39impl From<Value> for JsonPayload {
40    fn from(value: Value) -> Self {
41        Self(value)
42    }
43}
44
45impl From<JsonPayload> for Value {
46    fn from(value: JsonPayload) -> Self {
47        value.0
48    }
49}
50
51impl AsRef<Value> for JsonPayload {
52    fn as_ref(&self) -> &Value {
53        self.as_raw()
54    }
55}
56
57impl Deref for JsonPayload {
58    type Target = Value;
59
60    fn deref(&self) -> &Self::Target {
61        self.as_raw()
62    }
63}
64
65impl PartialEq<Value> for JsonPayload {
66    fn eq(&self, other: &Value) -> bool {
67        self.as_raw() == other
68    }
69}
70
71impl PartialEq<JsonPayload> for Value {
72    fn eq(&self, other: &JsonPayload) -> bool {
73        self == other.as_raw()
74    }
75}