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§
source§impl<'indent, W: Write> JsonGenerator<'indent, W>
impl<'indent, W: Write> JsonGenerator<'indent, W>
sourcepub fn new(out: W) -> Self
pub fn new(out: W) -> Self
Create a new JsonGenerator
object. The serialized byte sequence will be written to the given io::Write
object.
sourcepub fn indent(self, indent: &'indent str) -> Self
pub fn indent(self, indent: &'indent str) -> Self
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
]");
sourcepub fn generate(&mut self, value: &JsonValue) -> Result<()>
pub fn generate(&mut self, value: &JsonValue) -> Result<()>
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
]");