Function serde_json::de::from_reader

source ·
pub fn from_reader<R, T>(rdr: R) -> Result<T>where
    R: Read,
    T: DeserializeOwned,
Expand description

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.

It is expected that the input stream ends after the deserialized object. If the stream does not end, such as in the case of a persistent socket connection, this function will not return. It is possible instead to deserialize from a prefix of an input stream without looking for EOF by managing your own Deserializer.

Note that counter to intuition, this function is usually slower than reading a file completely into memory and then applying from_str or from_slice on it. See issue #160.

Example

Reading the contents of a file.

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<dyn 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);
}

Reading from a persistent socket connection.

use serde::Deserialize;

use std::error::Error;
use std::net::{TcpListener, TcpStream};

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

fn read_user_from_stream(tcp_stream: TcpStream) -> Result<User, Box<dyn Error>> {
    let mut de = serde_json::Deserializer::from_reader(tcp_stream);
    let u = User::deserialize(&mut de)?;

    Ok(u)
}

fn main() {
    let listener = TcpListener::bind("127.0.0.1:4000").unwrap();

    for stream in listener.incoming() {
        println!("{:#?}", read_user_from_stream(stream.unwrap()));
    }
}

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.