Serde and Serde_json

What's the difference between Serde and Serde_json, I am confused about this.

Serde is a generic library that acts as glue code between data structures and serialization formats. It doesn't know about any particular serialization format. In contrast, serde_json is the implementation of JSON as such a serde-compatible serialization format.

1 Like

the relation sounds like "slf4j" and "logback" in java, is it?
I also want to know that can I use serde_json without serde?

I'm sorry but I'm not familiar with the Java ecosystem. I did a quick google search, and the relation does sound similar, although there are important differences:

  • Serde is mainly a compile-time abstraction; serialization and deserialization functions are generic over the serializer/deseralizer type (ie., the data format).
  • Serde-compatible serialization formats are defined in terms of Serde's data structures and traits, so they can't be used without Serde.

No.

3 Likes

Ok,I got it. Thanks fro your help.

You can think of it in terms of Jackson and jackson-dataformat-yaml. You can make your objects serializable with Jackson, and then output YAML with jackson-dataformat-yaml, similar to how serde allows you to serialize the same objects to different formats like JSON with serde_json or YAML with serde_yaml.

Of course, this comparison is somewhat complicated by the fact that Jackson includes JSON functionality built-in (no need for external packages), while in case of Serde, it is separate (in serde_json crate).

1 Like

The more fine-grained model is that serde proper provides four "public" traits:

  • De/Serialize for types that can be de/serialized.
  • De/Serializer for formats that can de/serialize.

It also provides implementations for De/Serialize for built-in types, and with the derive feature enabled, it also exports derive macros for De/Serialize, so you can easily implement them for your own types, including customization using #[serde] attributes. These are just a re-export from serde_derive.

Formats like JSON in serde_json implement one or both of De/Serializer, and provide the entry points, eg serde_json::from_str(). These internally mostly just create a De/Serializerand call de/serialize() with them.

The connection between the two is that essentially (details around self-describing formats handwaved away), the De/Serialize types call methods on the De/Serializer formats to describe what structure, type and value the type contains, using a common vocabulary defined by serde.rs.

1 Like