Convert Figma logo to code with AI

serde-rs logoserde

Serialization framework for Rust

8,997
761
8,997
288

Top Related Projects

1,570

RustSec API & Tooling

4,815

Strongly typed JSON library for Rust

2,639

A binary encoder / decoder implementation in Rust.

Quick Overview

Serde is a framework for serializing and deserializing Rust data structures efficiently and generically. It provides a powerful and flexible system for converting Rust data types to and from various formats such as JSON, YAML, and MessagePack.

Pros

  • Highly performant and zero-copy deserialization
  • Supports a wide range of data formats
  • Extensive derive macros for automatic implementation
  • Customizable serialization and deserialization behavior

Cons

  • Learning curve for advanced usage and custom implementations
  • Can increase compile times due to heavy use of macros
  • Some formats require additional dependencies
  • Occasional complexity when dealing with complex data structures

Code Examples

  1. Basic serialization and deserialization:
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, Debug)]
struct Person {
    name: String,
    age: u8,
}

fn main() {
    let person = Person {
        name: "Alice".to_string(),
        age: 30,
    };

    // Serialize to JSON
    let json = serde_json::to_string(&person).unwrap();
    println!("Serialized: {}", json);

    // Deserialize from JSON
    let deserialized: Person = serde_json::from_str(&json).unwrap();
    println!("Deserialized: {:?}", deserialized);
}
  1. Custom serialization:
use serde::{Serialize, Serializer};

struct Point(i32, i32);

impl Serialize for Point {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut seq = serializer.serialize_tuple(2)?;
        seq.serialize_element(&self.0)?;
        seq.serialize_element(&self.1)?;
        seq.end()
    }
}
  1. Deserializing untagged enums:
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
enum Value {
    Integer(i64),
    Float(f64),
    String(String),
}

fn main() {
    let json = r#"[1, 2.5, "hello"]"#;
    let values: Vec<Value> = serde_json::from_str(json).unwrap();
    println!("{:?}", values);
}

Getting Started

To use Serde in your Rust project, add the following to your Cargo.toml:

[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"  # For JSON support

Then, in your Rust code:

use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, Debug)]
struct MyStruct {
    field1: String,
    field2: i32,
}

fn main() {
    let data = MyStruct {
        field1: "Hello".to_string(),
        field2: 42,
    };
    let serialized = serde_json::to_string(&data).unwrap();
    println!("Serialized: {}", serialized);
}

This example demonstrates basic usage of Serde with JSON serialization.

Competitor Comparisons

1,570

RustSec API & Tooling

Pros of RustSec

  • Focused on security auditing and vulnerability tracking for Rust projects
  • Provides a database of known security vulnerabilities in Rust crates
  • Offers tools for automated security scanning of Rust dependencies

Cons of RustSec

  • More specialized use case compared to Serde's broad serialization/deserialization functionality
  • Smaller community and ecosystem compared to Serde's widespread adoption
  • Less frequent updates and contributions due to its niche focus

Code Comparison

RustSec example (vulnerability definition):

[advisory]
id = "RUSTSEC-2021-0000"
package = "example_crate"
date = "2021-01-01"
categories = ["code-execution"]

Serde example (serialization):

#[derive(Serialize, Deserialize)]
struct Point {
    x: i32,
    y: i32,
}

While both projects are valuable for the Rust ecosystem, they serve different purposes. Serde is a general-purpose serialization framework, while RustSec focuses on security auditing. Serde has broader applicability and a larger user base, but RustSec fills a crucial niche in the Rust security landscape.

4,815

Strongly typed JSON library for Rust

Pros of json

  • Specialized for JSON serialization and deserialization
  • Simpler API for JSON-specific use cases
  • Potentially faster for JSON-only operations

Cons of json

  • Limited to JSON format only, less versatile than serde
  • Fewer customization options compared to serde's derive macros
  • Smaller ecosystem and fewer integrations with other crates

Code Comparison

serde:

#[derive(Serialize, Deserialize)]
struct Person {
    name: String,
    age: u8,
}

json:

#[derive(Serialize, Deserialize)]
struct Person {
    name: String,
    age: u8,
}

The code for defining serializable structs is identical in both cases. However, serde provides more flexibility for custom serialization:

serde:

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct CustomPerson {
    first_name: String,
    last_name: String,
}

json doesn't offer the same level of customization through attributes.

Both serde and json are part of the serde ecosystem, with json being a specialized JSON implementation built on top of serde. While json offers a more focused API for JSON operations, serde provides greater flexibility and support for multiple formats. The choice between them depends on the specific requirements of your project.

2,639

A binary encoder / decoder implementation in Rust.

Pros of bincode

  • Specialized for binary serialization, offering faster performance for this specific use case
  • Produces more compact binary output compared to general-purpose serialization formats
  • Simpler API for binary serialization/deserialization tasks

Cons of bincode

  • Limited to binary format only, lacking support for other serialization formats
  • Less flexibility in customizing serialization behavior
  • Smaller ecosystem and fewer integrations with other libraries

Code Comparison

Serde:

#[derive(Serialize, Deserialize)]
struct Point { x: i32, y: i32 }

let point = Point { x: 1, y: 2 };
let serialized = serde_json::to_string(&point).unwrap();

bincode:

#[derive(Serialize, Deserialize)]
struct Point { x: i32, y: i32 }

let point = Point { x: 1, y: 2 };
let serialized = bincode::serialize(&point).unwrap();

Both Serde and bincode use similar derive macros for serialization, but Serde offers more flexibility in choosing output formats (e.g., JSON, YAML), while bincode focuses solely on efficient binary serialization. Serde provides a more comprehensive serialization framework, while bincode excels in binary-specific use cases where performance and compact output are priorities.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Serde   Build Status Latest Version serde msrv serde_derive msrv

Serde is a framework for serializing and deserializing Rust data structures efficiently and generically.


You may be looking for:

Serde in action

Click to show Cargo.toml. Run this code in the playground.
[dependencies]

# The core APIs, including the Serialize and Deserialize traits. Always
# required when using Serde. The "derive" feature is only required when
# using #[derive(Serialize, Deserialize)] to make Serde work with structs
# and enums defined in your crate.
serde = { version = "1.0", features = ["derive"] }

# Each data format lives in its own crate; the sample code below uses JSON
# but you may be using a different one.
serde_json = "1.0"

use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug)]
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let point = Point { x: 1, y: 2 };

    // Convert the Point to a JSON string.
    let serialized = serde_json::to_string(&point).unwrap();

    // Prints serialized = {"x":1,"y":2}
    println!("serialized = {}", serialized);

    // Convert the JSON string back to a Point.
    let deserialized: Point = serde_json::from_str(&serialized).unwrap();

    // Prints deserialized = Point { x: 1, y: 2 }
    println!("deserialized = {:?}", deserialized);
}

Getting help

Serde is one of the most widely used Rust libraries so any place that Rustaceans congregate will be able to help you out. For chat, consider trying the #rust-questions or #rust-beginners channels of the unofficial community Discord (invite: https://discord.gg/rust-lang-community), the #rust-usage or #beginners channels of the official Rust Project Discord (invite: https://discord.gg/rust-lang), or the #general stream in Zulip. For asynchronous, consider the [rust] tag on StackOverflow, the /r/rust subreddit which has a pinned weekly easy questions post, or the Rust Discourse forum. It's acceptable to file a support issue in this repo but they tend not to get as many eyes as any of the above and may get closed without a response after some time.


License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in Serde by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.