Expand description
JSON (RFC 7159) decoder implementation.
The decoder supports direct decoding into Rust types (providing
helper macros such as object!) as well as generic decoding
using an intermediate representation.
§Example 1: Generic decoding
use json_codec_wasm::{Decoder, Json};
use json_codec_wasm::ast::Ref;
let json = r#"
{ "field1": true,
"field2": { "nested": [42, 73] }
}"#;
let mut d = Decoder::default(json.chars());
let v = d.decode().unwrap();
let r = Ref::new(&v);
assert_eq!(true, r.get("field1").bool().unwrap());
assert_eq!(73i128, r.get("field2").get("nested").at(1).i128().unwrap());
§Example 2: Direct decoding using macros
#[macro_use] extern crate json_codec_wasm;
use json_codec_wasm::Decoder;
const JSON: &'static str =
r#"
{
"Width": 800,
"Height": 600,
"Title": "View from 15th Floor",
"Thumbnail": {
"Url": "http://www.example.com/image/481989943",
"Height": 125,
"Width": 100
},
"Animated" : false,
"IDs": [116, 943, 234, 38793]
}
"#;
struct Image {
width: usize,
height: usize,
title: String,
thumbnail: Thumbnail,
animated: bool,
ids: Vec<u32>,
geo: Option<(i128, i128)>
}
struct Thumbnail {
url: String,
height: u16,
width: u16
}
let mut d = Decoder::default(JSON.chars());
let image = object! {
let decoder = d;
Image {
width: req. "Width" => d.usize(),
height: req. "Height" => d.usize(),
title: req. "Title" => d.string(),
thumbnail: req. "Thumbnail" => object! {
let decoder = d;
Thumbnail {
url: req. "Url" => d.string(),
height: req. "Height" => d.u16(),
width: req. "Width" => d.u16()
}
},
animated: req. "Animated" => d.bool(),
ids: req. "IDs" => array!(d, d.u32()),
geo: opt. "Geo" => d.optional(|d| {
let lat = d.i128()?;
let lon = d.i128()?;
Ok((lat, lon))
})
}
};
assert!(image.is_ok());Structs§
- Array
Iter - Iterator over JSON array elements.
- Config
- Decoder configuration.
- Decoder
- JSON decoder over
chariterators. - Read
Iter - Iterator over characters read from any
Read-type.