How to use a custom formatter with Serialize in serde_json?

Hello, I'm not able to connect a custom serde_json::Formatter to a Serialize implementation.

My goal is to be able to serialize the floats in my type with a fixed number of decimals.

I started with this example on using a custom formatter with serde_json::Serializer::with_formatter.

However, the example above gives me a Serializer, and I don't know how to plug that into the Serialize implementation for my BoundingVolume. I would like to do this, because BoundingVolume itself is part of other structs, which derive Serialize.

A playground of where I am currently: Rust Playground

Is it possible to do? Or did I mix up the serde concepts?

I think you'll have to do a little more work to be able to serialize correctly (luckily, not too much). You'll need to call directly into bounding_volume's serialization implementation. Here's a working example that prints out the serialized data:

fn main() {
    let bounding_volume = BoundingVolume::Region([
        0.0762316935076296,
        0.9075853268461559,
        0.07639433996161832,
        0.9076933035069118,
        38.18193225618456,
        96.3895906072444,
    ]);
    let out = std::io::stdout();
    
    // Construct a serializer from its output channel and formatter
    let mut ser = serde_json::ser::Serializer::with_formatter(
        out, 
        BoundingVolumeFormatter,
    );
    // now the value serializes into the serializer
    bounding_volume.serialize(&mut ser).unwrap();
}
2 Likes

Yes, I see, thank you!