使用 Serde 将 json 字符串序列化为对象

all*_*evo 4 serialization json rust serde

我有以下结构

#[derive(Serialize)]
pub struct MyStruct {
    pub id: String,
    pub score: f32,
    pub json: String,
}
Run Code Online (Sandbox Code Playgroud)

json字段始终包含已字符串化的有效 JSON 对象。

给定一个实例,我想使用 JSON 内容对其进行序列化。就像是:

let a = MyStruct {
    id: "my-id".to_owned(),
    score: 20.3,
    json: r#"{
       "ffo": 4
    }"#,
};
let r = to_string(&a).unwrap();
assert_eq!(r, r#"{
        "id": "my-id",
        "score": 20.3,
        "json": {
            "ffo": 4
        }
    }"#);
Run Code Online (Sandbox Code Playgroud)

注意:我不需要支持不同的序列化格式,只需要支持 JSON。NB2:我确信该json字段始终包含有效的 JSON 对象。NB3:我通常使用 serde,但我愿意使用不同的库。

我怎样才能做到这一点?

编辑:如果可能的话,我想避免在序列化过程中反序列化字符串。

isa*_*tfa 6

serde_json有一个raw_value类似这样的功能:

Cargo.toml

# ...
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = { version = "1.0", features = ["raw_value"] }
Run Code Online (Sandbox Code Playgroud)

lib.rs

use serde::{Serializer, Serialize};
use serde_json::{self, value::RawValue};

#[derive(Serialize)]
pub struct MyStruct {
    pub id: String,
    pub score: f32,
    #[serde(serialize_with = "serialize_raw_json")]
    pub json: String,
}

fn serialize_raw_json<S>(json: &str, s: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    // This should be pretty efficient: it just checks that the string is valid;
    // it doesn't parse it into a new data structure.
    let v: &RawValue = serde_json::from_str(json).expect("invalid json");
    v.serialize(s)
}

#[test]
fn test_serialize() {
    let a = MyStruct {
        id: "my-id".to_owned(),
        score: 20.3,
        json: r#"{
           "ffo": 4
        }"#
        .to_string(),
    };

    let r = serde_json::to_string(&a).unwrap();
    assert_eq!(
        r,
        r#"{"id":"my-id","score":20.3,"json":{
           "ffo": 4
        }}"#
    );
}
Run Code Online (Sandbox Code Playgroud)

但最简单(也是最容易出错且最不可扩展)的解决方案是简单的字符串操作:

#[derive(Serialize)]
pub struct MyStruct {
    pub id: String,
    pub score: f32,
    // IMPORTANT: don't serialize this field at all
    #[serde(skip)]
    pub json: String,
}

fn serialize(a: &MyStruct) -> String {
    let mut r = serde_json::to_string(&a).unwrap();

    // get rid of trailing '}'
    r.pop();
    // push the key
    r.push_str(r#","json":"#);
    // push the value
    r.push_str(&a.json);
    // push the closing brace
    r.push('}');
    
    r
}

#[test]
fn test_serialize() {
    let a = MyStruct {
        id: "my-id".to_owned(),
        score: 20.3,
        json: r#"{
           "ffo": 4
        }"#
        .to_string(),
    };

    let r = serialize(&a);
    assert_eq!(
        r,
        r#"{"id":"my-id","score":20.3,"json":{
           "ffo": 4
        }}"#
    );
}
Run Code Online (Sandbox Code Playgroud)