pub trait JSONValue {
// Required method
fn write_json<W: Write>(&self, w: &mut W) -> Result<()>;
// Provided methods
fn to_json_string(&self) -> String { ... }
fn to_json_buffer(&self) -> Vec<u8> ⓘ { ... }
}Expand description
A trait implemented by types that can be serialized to JSON
This trait can be derived for custom structs using json_in_type_derive
Required Methods§
Provided Methods§
Sourcefn to_json_string(&self) -> String
fn to_json_string(&self) -> String
Returns the object formatted as a json string
§Panics
If you implement JSONValue on your own types and emit invalid UTF-8 in write_json. If you use the implementations of JSONValue provided in this library, this function will never panic.
Sourcefn to_json_buffer(&self) -> Vec<u8> ⓘ
fn to_json_buffer(&self) -> Vec<u8> ⓘ
Returns a buffer containing the bytes of a json representation of the object
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".
Implementations on Foreign Types§
Source§impl<K: JSONString + Eq + Hash, V: JSONValue, S: BuildHasher> JSONValue for HashMap<K, V, S>
Serialize a HashMap to a JSON object. The property order is not guaranteed.
impl<K: JSONString + Eq + Hash, V: JSONValue, S: BuildHasher> JSONValue for HashMap<K, V, S>
Serialize a HashMap to a JSON object. The property order is not guaranteed.
Source§impl<T: JSONValue, I: Iterator<Item = T>> JSONValue for RefCell<I>
Allows to serialize an iterator to JSON in a streaming fashion.
The iterator needs to be wrapped in a RefCell because it will be consumed
as JSON is written.
impl<T: JSONValue, I: Iterator<Item = T>> JSONValue for RefCell<I>
Allows to serialize an iterator to JSON in a streaming fashion. The iterator needs to be wrapped in a RefCell because it will be consumed as JSON is written.
§Examples
§Serialize an iterator JSON
use std::cell::RefCell;
use std::iter::repeat;
use json_in_type::JSONValue;
let my_iter = repeat(42).take(3);
let my_iter_cell = RefCell::new(my_iter);
// The iterator will be consumed as json is produced
assert_eq!("[42,42,42]", my_iter_cell.to_json_string());
// Here, the iterator has already been consumed, so there is nothing left to serialize
assert_eq!("[]", my_iter_cell.to_json_string());§Write a large JSON to a file
In this example, we take a potentially large input file, and serialize it to a JSON file containing an array with all the lines from the input file.
The output should look like this:
[
{"line": 1, "contents": "a line of text"},
{"line": 2, "contents": "another line of text"}
]use std::cell::RefCell;
use std::io::BufRead;
use std::io::BufReader;
use json_in_type::*;
let json_lines = BufReader::new(input_file)
.lines()
.map(|l| l.unwrap())
.enumerate()
.map(|(i, contents)| json_object!{line:i+1, contents:contents});
RefCell::new(json_lines).write_json(&mut output_file);