Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created November 18, 2018 22:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rust-play/948cd52efb44463c24ab6d9ad37d3d12 to your computer and use it in GitHub Desktop.
Save rust-play/948cd52efb44463c24ab6d9ad37d3d12 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use serde::Deserializer;
use serde_derive::Deserialize;
fn non_empty_str<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
use serde::Deserialize;
let o: Option<String> = Option::deserialize(d)?;
Ok(o.filter(|s| !s.is_empty()))
}
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum LocalModList {
V1(Vec<LocalMod>),
V2(LocalModListV2),
}
#[derive(Debug, Deserialize)]
struct LocalModListV2 {
#[serde(rename = "modList")]
pub mod_list: Vec<LocalMod>,
}
#[derive(Debug, Deserialize)]
struct LocalMod {
pub modid: String,
pub name: String,
pub version: String,
#[serde(rename = "updateUrl")]
#[serde(deserialize_with = "non_empty_str")]
pub update_url: Option<String>,
#[serde(rename = "updateJSON")]
#[serde(deserialize_with = "non_empty_str")]
pub update_json: Option<String>,
}
fn main() {
let json =
r#"[
{
"modid": "quark",
"name": "Quark",
"description": "Small things.",
"version": "r1.5-130",
"mcversion": "1.12.2",
"logoFile": "",
"url": "http://www.vazkii.us",
"updateUrl": "",
"authorList": ["Vazkii", "wiiv"],
"credits": "",
"parent": "",
"screenshots": [],
"dependencies": []
}
]"#;
let localmods = serde_json::from_str::<LocalModList>(json);
println!("{:#?}", localmods);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment