Struct tinyjson::JsonGenerator

source ·
pub struct JsonGenerator<'indent, W: Write> { /* private fields */ }
Expand description

JSON serializer for JsonValue.

Basically you don’t need to use this struct directly since JsonValue::stringify or JsonValue::format methods are using this internally.

use tinyjson::{JsonGenerator, JsonValue};

let v = JsonValue::from("hello, world".to_string());
let mut buf = vec![];
let mut gen = JsonGenerator::new(&mut buf);
gen.generate(&v).unwrap();

assert_eq!(String::from_utf8(buf).unwrap(), "\"hello, world\"");

Implementations§

Create a new JsonGenerator object. The serialized byte sequence will be written to the given io::Write object.

Set indent string. This will be used by JsonGenerator::generate.

use tinyjson::{JsonGenerator, JsonValue};

let v = JsonValue::from(vec![1.0.into(), 2.0.into(), 3.0.into()]);
let mut buf = vec![];
let mut gen = JsonGenerator::new(&mut buf).indent("        ");
gen.generate(&v).unwrap();

assert_eq!(String::from_utf8(buf).unwrap(),
"[
        1,
        2,
        3
]");

Serialize the JsonValue into UTF-8 byte sequence. The result will be written to the io::Write object passed at JsonGenerator::new. This method serializes the value without indentation by default. But after setting an indent string via JsonGenerator::indent, this method will use the indent for elements of array and object.

use tinyjson::{JsonGenerator, JsonValue};

let v = JsonValue::from(vec![1.0.into(), 2.0.into(), 3.0.into()]);

let mut buf = vec![];
let mut gen = JsonGenerator::new(&mut buf);
gen.generate(&v).unwrap();
assert_eq!(String::from_utf8(buf).unwrap(), "[1,2,3]");

let mut buf = vec![];
let mut gen = JsonGenerator::new(&mut buf).indent("  "); // with 2-spaces indent
gen.generate(&v).unwrap();

assert_eq!(String::from_utf8(buf).unwrap(),
"[
  1,
  2,
  3
]");

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.