Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Remove ToJson trait #294

Closed
dtolnay opened this issue Apr 11, 2017 · 2 comments
Closed

Remove ToJson trait #294

dtolnay opened this issue Apr 11, 2017 · 2 comments
Milestone

Comments

@dtolnay
Copy link
Member

dtolnay commented Apr 11, 2017

This trait was ripped directly from rustc_serialize::json::ToJson but the point was lost by providing an impl ToJson for T where T: Serialize. The rustc_serialize trait is infallible and there are impls for standard library types that can be infallibly converted to Json - not for all types that implement Encodable.

I don't think the trait as it currently exists serves a purpose. The fallible use case is covered by serde_json::to_value and the literal use case is covered by the json! macro.

I would be open to seeing an infallible ToJson trait explored in its own crate - ideally complete with its own custom derive which is distinct from serde's Serialize.

#[derive(ToJson)]
struct S {
    a: u8,
    b: u8,
}

// The generated code:
impl ToJson for S {
    fn to_json(&self) -> serde_json::Value {
        json!({
            "a": ToJson::to_json(&self.a),
            "b": ToJson::to_json(&self.b),
        })
    }
}
@dtolnay dtolnay added this to the v1.0 milestone Apr 11, 2017
@dtolnay
Copy link
Member Author

dtolnay commented Apr 11, 2017

Fixed in #295.

@lilyball
Copy link

D'oh. I was using this trait for a type that I wanted to be able to convert to JSON but which I didn't want to make generically serializable. The reason being, I have a specific JSON format I need to match, so my ToJson implementation is written for that format. But that format isn't the "natural" format for my data structure. In fact, I have a separate XML format too that I emit (but I don't use Serde at all for that, I use a custom XML serializer), which definitely doesn't match the JSON format. I'm also not even sure if it's possible to get the JSON structure I need using Serializable.

The main fallout here is I won't be able to use my type with json! anymore. I can certainly work around that limitation, but it's annoying, and surely I'm not the only person who has a type that needs precise control over its JSON representation.

# for free to join this conversation on GitHub. Already have an account? # to comment
Development

No branches or pull requests

2 participants