fdeantoni / prost-wkt

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

Convert between prost_wkt_types::Value and serde_json::Value? #47

Open AlJohri opened 1 year ago

AlJohri commented 1 year ago

Is there any examples of how to convert between these two types? Or how to go from a rust struct to google.protobuf.Value? I thought with the serde support we would get this out of the box, but I am running into this error:

error[E0277]: the trait bound `prost_wkt_types::Value: From<serde_json::Value>` is not satisfied
   --> src/tonic.rs:108:55
    |
108 |         let aaaaaaaaaa = prost_wkt_types::Value::from(aaaaaaaaaa);
    |                          ---------------------------- ^^^^^^^^^^ the trait `From<serde_json::Value>` is not implemented for `prost_wkt_types::Value`
    |                          |
    |                          required by a bound introduced by this call
    |
    = help: the following other types implement trait `From<T>`:
              <prost_wkt_types::Value as From<HashMap<std::string::String, prost_wkt_types::Value>>>
              <prost_wkt_types::Value as From<Vec<prost_wkt_types::Value>>>
              <prost_wkt_types::Value as From<bool>>
              <prost_wkt_types::Value as From<f64>>
              <prost_wkt_types::Value as From<prost_wkt_types::NullValue>>
              <prost_wkt_types::Value as From<std::string::String>>

I documented how I was able to do this manually without prost-wkt in this StackOverflow answer, but it would be great to use the Serialize/Deserialize machinery here.

AlJohri commented 1 year ago

Ah, looks like I need to use serde_json::from_value as opposed to prost_wkt_types::Value::from like so:

let aaaaaaaaaa = MyRustStruct::default();
let aaaaaaaaaa = serde_json::to_value(aaaaaaaaaa)?
let aaaaaaaaaa: prost_wkt_types::Value = serde_json::from_value(aaaaaaaaaa)?

I think this issue can be closed although I'd be curious why we don't implement prost_wkt_types::Value::from for serde_json::Value?

fdeantoni commented 1 year ago

For my use case there was no reason yet to implement this but I suppose it can be added. I'm not sure yet if this should be a From or a TryFrom.