fdeantoni / prost-wkt

Prost Well-Known-Types serialization and deserialization.
Apache License 2.0
75 stars 37 forks source link

serde_json::Value into prost_wkt_types::Value? #21

Closed dragonnn closed 2 years ago

dragonnn commented 2 years ago

Hi! I have a struct from my database with contains serde_json::Value (since that filed in the db is jsonb) and I need to send it over grpc, is they any simple way to convert it into prost_wkt_types::Value. I think that would be the right struct to hold it. Is they any reason it doesn't implement that or is just missing at the moment?

fdeantoni commented 2 years ago

It is actually possible to convert a serde_json::Value to prost_wkt_types::Value, but unfortunately the other way around is not implemented. For that you need to serialize it first to something that both understand, like string (or your own struct that implements Serialize/Deserialize).

Here a small test that shows the conversion to and from:

#[test]
fn convert_serde_json_test() {
    let data = r#"{
        "string":"hello",
        "timestamp":"1970-01-01T00:01:39.000000042Z",
        "boolean":true,
        "data": {
            "test_number": 1.0,
            "test_bool": true,
            "test_string": "hi there",
            "test_list": [1.0, 2.0, 3.0, 4.0],
            "test_inner_struct": {
            "one": 1.0,
            "two": 2.0
            }
        },
        "list": []
        }"#;
        let sj: serde_json::Value = serde_json::from_str(data).unwrap();
        let pj: prost_wkt_types::Value = serde_json::from_value(sj.clone()).unwrap();
        println!("prost_wkt_types Value: {:?}", &pj);
        let string: String = serde_json::to_string(&pj).unwrap();
        let back: serde_json::Value = serde_json::from_str(&string).unwrap();
        assert_eq!(sj, back);
}

Is this what you are looking for or did I misunderstand?

dragonnn commented 2 years ago

Yes, this is exactly what I need, I didn't think about using from_value for doing that. Thanks! That solves my problem