Guide: Serializing Data - louisphilipmarcoux/rill-json GitHub Wiki

rill-json includes a serializer that can convert native Rust data structures into a JSON string. It does this using the JsonValue enum.

You must build a JsonValue instance yourself, and then you can call .stringify() or .stringify_pretty() on it.


Building a JsonValue

The JsonValue enum has variants that map directly to JSON types:

  • JsonValue::Null
  • JsonValue::Boolean(bool)
  • JsonValue::Number(JsonNumber) (Using the JsonNumber enum)
  • JsonValue::String(String)
  • JsonValue::Array(Vec<JsonValue>)
  • JsonValue::Object(BTreeMap<String, JsonValue>)

Note on BTreeMap: We use BTreeMap (not HashMap) for objects. This guarantees that your JSON output will always have its keys sorted alphabetically. This is crucial for deterministic serialization and testing.

Example: Creating a Complex Object

use rill_json::{JsonValue, JsonNumber};
use std::collections::BTreeMap; // <-- Use BTreeMap!

// 1. Create native Rust data
let mut user_data = BTreeMap::new(); // <-- Use BTreeMap! [cite: 59]

user_data.insert(
    "username".to_string(),
    JsonValue::String("ada_l".to_string()) [cite: 60]
);
user_data.insert(
    "id".to_string(),
    JsonValue::Number(JsonNumber::I64(1815)) // <-- Use JsonNumber! [cite: 60]
);
user_data.insert(
    "projects".to_string(),
    JsonValue::Array(vec![
        JsonValue::String("Analytical Engine".to_string()),
        JsonValue::String("Difference Engine".to_string())
    ]) [cite: 61]
);
user_data.insert(
    "active".to_string(),
    JsonValue::Boolean(false) [cite: 62]
);

// 2. Wrap it in the JsonValue::Object variant
let json_object = JsonValue::Object(user_data);

// 3. Stringify it! [cite: 63]

// --- Compact Version ---
// Ideal for sending over a network.
// Note: stringify() returns a Result!
match json_object.stringify() { [cite: 50]
    Ok(compact_string) => { [cite: 64]
        println!("{}", compact_string);
        // Output (keys are sorted alphabetically):
        // {"active":false,"id":1815,"projects":["Analytical Engine","Difference Engine"],"username":"ada_l"}
    }
    Err(e) => println!("Error: {}", e),
}


// --- Pretty Version ---
// Ideal for logging or saving to a config file.
match json_object.stringify_pretty() { [cite: 65]
    Ok(pretty_string) => {
        println!("{}", pretty_string);
        // Output (keys are sorted alphabetically):
        // {
        //   "active": false,
        //   "id": 1815,
        //   "projects": [
        //     "Analytical Engine",
        //     "Difference Engine"
        //   ],
        //   "username": "ada_l"
        // }
    }
    Err(e) => println!("Error: {}", e),
}
⚠️ **GitHub.com Fallback** ⚠️