| Crates.io | json-result |
| lib.rs | json-result |
| version | 0.1.1 |
| created_at | 2025-12-03 15:12:44.685304+00 |
| updated_at | 2025-12-07 06:07:16.255504+00 |
| description | A generic enum representing a JSON result that can either be a success (`Ok`) with a value of type `T` or an error (`Err`) with a value of type `E`. |
| homepage | https://github.com/LorenzoLeonardo/json-result |
| repository | https://github.com/LorenzoLeonardo/json-result |
| max_upload_size | |
| id | 1964219 |
| size | 36,592 |
JsonResult is a Rust generic enum designed for seamlessly handling JSON values that can represent either a success (Ok) or error (Err) result, with flexible types. It integrates tightly with Serde for serialization and deserialization.
serde_json::Value easily.T) and error (E) types.Add this to your Cargo.toml:
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
use serde_json::json;
use std::convert::TryFrom;
let success_json = json!({"id": 1, "name": "Alice"});
let error_json = json!({"error_code": 404, "message": "Not Found"});
// Define your success and error types
#[derive(serde::Deserialize, serde::Serialize, Debug)]
struct User {
id: u32,
name: String,
}
#[derive(serde::Deserialize, serde::Serialize, Debug)]
struct ApiError {
error_code: u16,
message: String,
}
type MyJsonResult = JsonResult<User, ApiError>;
// Deserialize JSON into JsonResult
let res_ok: MyJsonResult = success_json.try_into().unwrap();
let res_err: MyJsonResult = error_json.try_into().unwrap();
match res_ok {
JsonResult::Ok(user) => println!("User: {:?}", user),
JsonResult::Err(e) => println!("Error: {:?}", e),
}
match res_err {
JsonResult::Ok(user) => println!("User: {:?}", user),
JsonResult::Err(e) => println!("Error: {:?}", e),
}
// Convert JsonResult back to serde_json::Value
let json_val: serde_json::Value = res_ok.into();
println!("Serialized back to JSON: {}", json_val);