Module json::decoder
[−]
[src]
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::{Decoder, Json}; use json::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!(73f64, r.get("field2").get("nested").at(1).number().unwrap());
Example 2: Direct decoding using macros
#[macro_use] extern crate json; use json::{Decoder, DecodeError, DecodeResult, Utf8Buffer}; 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<(f64, f64)> } struct Thumbnail { url: String, height: u16, width: u16 } let mut d = Decoder::default(JSON.chars()); let mut b = [0; 16]; let mut s = Utf8Buffer::new(&mut b); let image = object! { let decoder = d; let buffer = &mut s; Image { width: req. "Width" => Decoder::usize, height: req. "Height" => Decoder::usize, title: req. "Title" => Decoder::string, thumbnail: req. "Thumbnail" => |d| object! { let decoder = d; let buffer = &mut s; Thumbnail { url: req. "Url" => Decoder::string, height: req. "Height" => Decoder::u16, width: req. "Width" => Decoder::u16 } }, animated: req. "Animated" => Decoder::bool, ids: req. "IDs" => array!(Decoder::u32), geo: opt. "Geo" => |d| d.optional(|d| { let lat = try!(d.f64()); let lon = try!(d.f64()); Ok((lat, lon)) }) } }; assert!(image.is_ok());
Structs
ArrayIter |
Iterator over JSON array elements. |
Config |
Decoder configuration. |
Decoder |
JSON decoder over |
Element |
JSON array element. |
ReadIter |
Iterator over characters read from any |
Enums
DecodeError | |
ReadError |
Type Definitions
DecodeResult |