Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Comments on Handling JSON files in Rust without manually creating mapping classes
Post
Handling JSON files in Rust without manually creating mapping classes
I have JSON that looks something like this:
{"id":"n-fsdf-6b6",
"name":"JohnSmith",
"revisionDate":1591072274000}
The JSON data is named CharacterInfo
. It comes from a static external URL. The structure of this information could be changed, as it comes from an outside source and updates occur.
In rust the mapping class using Serede looks something like this:
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct CharacterInfo {
pub id: String,
pub name: String,
#[serde(rename = "revisionDate")]
pub revision_date i64:
}
The CharacterInfo
class needs to be referenced in code. It's an API wrapper library, so the method looks something like this:
pub fn get_character_info() -> Result<CharacterInfo, HttpError> {
let http_result = HttpClient::get(Self::CHARACTER_INFO_URL);
match http_result {
Ok(result) => {
let character_info: CharacterInfo = serde_json::from_str(&result).unwrap();
Ok(character_info)
}
Err(error) => Err(error),
}
}
The problem is the JSON files could change and there are a lot of them. Generating them manually would be tedius.
Generating the .rs
mapping classes Is not that difficult, in fact websites already exist to do this (https://transform.tools/json-to-rust-serde).
But I'm not sure how I could have my Rust program compile or use the .rs files after creating. Also would this be considered hacky / bad practice? Is there a better way?
1 comment thread