[][src]Function gltf_json::deserialize::from_reader

pub fn from_reader<R, T>(rdr: R) -> Result<T, Error> where
    R: Read,
    T: DeserializeOwned

Deserialize an instance of type T from an IO stream of JSON.

The content of the IO stream is deserialized directly from the stream without being buffered in memory by serde_json.

When reading from a source against which short reads are not efficient, such as a File, you will want to apply your own buffering because serde_json will not buffer the input. See std::io::BufReader.

Example

This code runs with edition 2018
use serde::Deserialize;

use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use std::path::Path;

#[derive(Deserialize, Debug)]
struct User {
    fingerprint: String,
    location: String,
}

fn read_user_from_file<P: AsRef<Path>>(path: P) -> Result<User, Box<Error>> {
    // Open the file in read-only mode with buffer.
    let file = File::open(path)?;
    let reader = BufReader::new(file);

    // Read the JSON contents of the file as an instance of `User`.
    let u = serde_json::from_reader(reader)?;

    // Return the `User`.
    Ok(u)
}

fn main() {
    let u = read_user_from_file("test.json").unwrap();
    println!("{:#?}", u);
}

Errors

This conversion can fail if the structure of the input does not match the structure expected by T, for example if T is a struct type but the input contains something other than a JSON map. It can also fail if the structure is correct but T's implementation of Deserialize decides that something is wrong with the data, for example required struct fields are missing from the JSON map or some number is too big to fit in the expected primitive type.