Last active
November 24, 2023 12:43
-
-
Save SCP002/c23feb339666fb57ba56e4e0ba06357c to your computer and use it in GitHub Desktop.
Rust: Serialize & Deserialize partially known / dynamic JSON. Using structs (type safe).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Add to your Cargo.toml: | |
// [dependencies] | |
// serde = { version = "1.0.193", features = ["derive"] } | |
// serde_json = "1.0.108" | |
use serde::{Deserialize, Serialize}; | |
use serde_json::{Map, Value}; | |
#[derive(Serialize, Deserialize)] | |
struct TopStruct { | |
#[serde(rename(serialize = "topKnownKey", deserialize = "topKnownKey"))] | |
top_known_key: i32, | |
#[serde(rename(serialize = "nestedKnownArray", deserialize = "nestedKnownArray"))] | |
nested_known_array: Vec<NestedStruct>, | |
#[serde(skip_serializing, skip_deserializing)] | |
excluded_known_key: i32, // Field sample for internal needs, excluded from JSON processing. | |
#[serde(flatten)] | |
unknown: Map<String, Value>, // All unknown fields go here. | |
} | |
#[derive(Serialize, Deserialize)] | |
struct NestedStruct { | |
#[serde(rename(serialize = "nestedKnownKey", deserialize = "nestedKnownKey"))] | |
nested_known_key: i32, | |
#[serde(skip_serializing, skip_deserializing)] | |
excluded_known_key: i32, // Field sample for internal needs, excluded from JSON processing. | |
#[serde(flatten)] | |
unknown: Map<String, Value>, // All unknown fields go here. | |
} | |
fn main() { | |
let input = r#" | |
{ | |
"topKnownKey": 1, | |
"topUnknownKey": 2, | |
"nestedKnownArray": [ | |
{ | |
"nestedKnownKey": 3, | |
"nestedUnknownKey": 4 | |
}, | |
{ | |
"nestedKnownKey": 5, | |
"nestedUnknownKey": 6 | |
} | |
], | |
"nestedUnknownArray": [ | |
{ | |
"nestedKnownKey": 7, | |
"nestedUnknownKey": 8 | |
} | |
] | |
} | |
"#; | |
// Decode. | |
let mut ts: TopStruct = match serde_json::from_str(input) { | |
Ok(ts) => ts, | |
Err(err) => panic!("Error decoding struct: {:?}", err), | |
}; | |
// Modify. | |
ts.top_known_key = 100; | |
ts.excluded_known_key = 200; | |
ts.nested_known_array[0].nested_known_key = 300; | |
ts.nested_known_array[0].excluded_known_key = 400; | |
// Encode. | |
let out: String = match serde_json::to_string_pretty(&ts) { | |
Ok(s) => s, | |
Err(err) => panic!("Error encoding struct: {:?}", err), | |
}; | |
// Print output. | |
println!("{}", out); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment