Trait struson::writer::JsonWriter
source · pub trait JsonWriter {
Show 14 methods
// Required methods
fn begin_object(&mut self) -> Result<(), Error>;
fn end_object(&mut self) -> Result<(), Error>;
fn begin_array(&mut self) -> Result<(), Error>;
fn end_array(&mut self) -> Result<(), Error>;
fn name(&mut self, name: &str) -> Result<(), Error>;
fn null_value(&mut self) -> Result<(), Error>;
fn bool_value(&mut self, value: bool) -> Result<(), Error>;
fn string_value(&mut self, value: &str) -> Result<(), Error>;
fn string_value_writer(
&mut self
) -> Result<impl StringValueWriter + '_, Error>;
fn number_value_from_string(
&mut self,
value: &str
) -> Result<(), JsonNumberError>;
fn number_value<N: FiniteNumber>(&mut self, value: N) -> Result<(), Error>;
fn fp_number_value<N: FloatingPointNumber>(
&mut self,
value: N
) -> Result<(), JsonNumberError>;
fn serialize_value<S: Serialize>(
&mut self,
value: &S
) -> Result<(), SerializerError>;
fn finish_document(self) -> Result<(), Error>;
}
Expand description
A trait for JSON writers
The methods of this writer can be divided into the following categories:
- Writing values
begin_array
,end_array
: Starting and ending a JSON arraybegin_object
,end_object
: Starting and ending a JSON objectname
: Writing a JSON object member namestring_value
,string_value_writer
: Writing a JSON string valuenumber_value
,fp_number_value
,number_value_from_string
: Writing a JSON number valuebool_value
: Writing a JSON boolean valuenull_value
: Writing a JSON null valueserialize_value
: Serializes a SerdeSerialize
as next value (optional feature)
- Other:
finish_document
: Ensuring that the JSON document is complete and flushing the buffer
JSON documents have at least one top-level value which can be either a JSON array, object,
string, number, boolean or null value. For JSON arrays and objects the opening brackets
must be written with the corresponding begin_
method (for example begin_array
) and the
closing bracket with the corresponding end_
method (for example end_array
). JSON objects
consist of members which are name-value pairs. The name of a member can be written with
name
and the value with any of the value writing methods such as bool_value
.
Once the JSON document is complete, finish_document
has to be called to ensure that the
JSON document really is complete and to flush the internal buffer to the underlying writer.
Forgetting to call finish_document
leads to unspecified behavior; most likely the written
JSON document will be incomplete. However, no undefined behavior occurs.
§Examples
// In this example JSON bytes are stored in a Vec;
// normally they would be written to a file or network connection
let mut writer = Vec::<u8>::new();
let mut json_writer = JsonStreamWriter::new(&mut writer);
json_writer.begin_object()?;
json_writer.name("a")?;
json_writer.begin_array()?;
json_writer.number_value(1)?;
json_writer.bool_value(true)?;
json_writer.end_array()?;
json_writer.end_object()?;
// Ensures that the JSON document is complete and flushes the buffer
json_writer.finish_document()?;
let json = String::from_utf8(writer)?;
assert_eq!(json, r#"{"a":[1,true]}"#);
§Error handling
The methods of this writer return a Result::Err
when an error occurs while writing
the JSON document. In most cases the error can only be an IO error which was caused
by the underlying writer. When encountering such an error, writing the JSON document
must be aborted. Trying to call any writer methods afterwards can lead to unspecified
behavior, such as errors, panics or incorrect data. However, no undefined behavior occurs.
In general it is recommended to handle errors with the ?
operator of Rust, for example
json_writer.bool_value(true)?
and to abort writing the JSON document when an error occurs.
§Panics
Methods of this writer panic when used in an incorrect way. The documentation of the methods
describes in detail the situations when that will happen. In general all these cases are
related to incorrect usage by the user (such as trying to call end_object
when currently
writing a JSON array).
Required Methods§
sourcefn begin_object(&mut self) -> Result<(), Error>
fn begin_object(&mut self) -> Result<(), Error>
Begins writing a JSON object
To write member of the object first call name
to write the member name
and afterwards one of the value writing to write the member value. At the end
call end_object
to write the closing bracket of the JSON object.
§Examples
let mut writer = Vec::<u8>::new();
let mut json_writer = JsonStreamWriter::new(&mut writer);
json_writer.begin_object()?;
json_writer.name("a")?;
json_writer.number_value(1)?;
json_writer.end_object()?;
json_writer.finish_document()?;
let json = String::from_utf8(writer)?;
assert_eq!(json, r#"{"a":1}"#);
§Panics
Panics when called on a JSON writer which currently expects a member name, or
when called after the top-level value has already been written and multiple top-level
values are not enabled in the WriterSettings
. Both cases indicate incorrect
usage by the user.
sourcefn end_object(&mut self) -> Result<(), Error>
fn end_object(&mut self) -> Result<(), Error>
Writes the closing bracket }
of the current JSON object
This method is used to end a JSON object started by begin_object
.
§Panics
Panics when called on a JSON writer which is currently not inside a JSON object, or when the value of a member is currently expected. Both cases indicate incorrect usage by the user.
sourcefn begin_array(&mut self) -> Result<(), Error>
fn begin_array(&mut self) -> Result<(), Error>
Begins writing a JSON array
To write items of the array the regular value writing methods such as number_value
can be used. At the end call end_array
to write the closing bracket of the JSON array.
Note that JSON arrays can contain values of different types, so for example the
following is valid JSON: [1, true, "a"]
§Examples
let mut writer = Vec::<u8>::new();
let mut json_writer = JsonStreamWriter::new(&mut writer);
json_writer.begin_array()?;
json_writer.number_value(1)?;
json_writer.end_array()?;
json_writer.finish_document()?;
let json = String::from_utf8(writer)?;
assert_eq!(json, "[1]");
§Panics
Panics when called on a JSON writer which currently expects a member name, or
when called after the top-level value has already been written and multiple top-level
values are not enabled in the WriterSettings
. Both cases indicate incorrect
usage by the user.
sourcefn end_array(&mut self) -> Result<(), Error>
fn end_array(&mut self) -> Result<(), Error>
Writes the closing bracket ]
of the current JSON object
This method is used to end a JSON array started by begin_array
.
§Panics
Panics when called on a JSON writer which is currently not inside a JSON array. This indicates incorrect usage by the user.
sourcefn name(&mut self, name: &str) -> Result<(), Error>
fn name(&mut self, name: &str) -> Result<(), Error>
Writes the name of the next JSON object member
Afterwards one of the value writing methods such as number_value
can be used
to write the corresponding member value.
This method does not detect or prevent duplicate member names, such as in
{"a": 1, "a": 2}
. Duplicate member names should be avoided because not all JSON
parsers might support them, and the way they are processed might not be consistent
between different JSON libraries.
Characters are automatically escaped in the JSON output if necessary. For example
the character U+0000 is written as \u0000
.
§Examples
let mut writer = Vec::<u8>::new();
let mut json_writer = JsonStreamWriter::new(&mut writer);
json_writer.begin_object()?;
json_writer.name("a")?;
json_writer.number_value(1)?;
json_writer.end_object()?;
json_writer.finish_document()?;
let json = String::from_utf8(writer)?;
assert_eq!(json, r#"{"a":1}"#);
§Panics
Panics when called on a JSON writer which currently does not expect a member name. This indicates incorrect usage by the user.
sourcefn null_value(&mut self) -> Result<(), Error>
fn null_value(&mut self) -> Result<(), Error>
Writes a JSON null value
This method takes no argument because there is only one JSON null value, which has no variants.
§Examples
let mut writer = Vec::<u8>::new();
let mut json_writer = JsonStreamWriter::new(&mut writer);
json_writer.null_value()?;
json_writer.finish_document()?;
let json = String::from_utf8(writer)?;
assert_eq!(json, "null");
§Panics
Panics when called on a JSON writer which currently expects a member name, or
when called after the top-level value has already been written and multiple top-level
values are not enabled in the WriterSettings
. Both cases indicate incorrect
usage by the user.
sourcefn bool_value(&mut self, value: bool) -> Result<(), Error>
fn bool_value(&mut self, value: bool) -> Result<(), Error>
Writes a JSON boolean value
§Examples
let mut writer = Vec::<u8>::new();
let mut json_writer = JsonStreamWriter::new(&mut writer);
json_writer.bool_value(true)?;
json_writer.finish_document()?;
let json = String::from_utf8(writer)?;
assert_eq!(json, "true");
§Panics
Panics when called on a JSON writer which currently expects a member name, or
when called after the top-level value has already been written and multiple top-level
values are not enabled in the WriterSettings
. Both cases indicate incorrect
usage by the user.
sourcefn string_value(&mut self, value: &str) -> Result<(), Error>
fn string_value(&mut self, value: &str) -> Result<(), Error>
Writes a JSON string value
This method is only intended to write string values, it cannot be used to write
JSON object member names. The method name
has to be used for that.
To avoid having to store the complete string value in memory, the method string_value_writer
can be used to obtain a writer which allows lazily writing the value. Especially for
large string values this can be useful.
Characters are automatically escaped in the JSON output if necessary. For example
the character U+0000 is written as \u0000
.
§Examples
let mut writer = Vec::<u8>::new();
let mut json_writer = JsonStreamWriter::new(&mut writer);
json_writer.string_value("text with \"quotes\"")?;
json_writer.finish_document()?;
let json = String::from_utf8(writer)?;
assert_eq!(json, r#""text with \"quotes\"""#);
§Panics
Panics when called on a JSON writer which currently expects a member name, or
when called after the top-level value has already been written and multiple top-level
values are not enabled in the WriterSettings
. Both cases indicate incorrect
usage by the user.
sourcefn string_value_writer(&mut self) -> Result<impl StringValueWriter + '_, Error>
fn string_value_writer(&mut self) -> Result<impl StringValueWriter + '_, Error>
Provides a writer for lazily writing a JSON string value
This method is mainly designed to write large string values in a memory efficient
way. If that is not a concern the method string_value
should be used instead.
This method is only intended to write string values, it cannot be used to write
JSON object member names. The method name
has to be used for that.
Characters are automatically escaped in the JSON output if necessary. For example
the character U+0000 is written as \u0000
.
Important: Once the string value is finished, StringValueWriter::finish_value
must be called. Otherwise the string value writer will still be considered ‘active’
and all methods of this JSON writer will panic.
§Examples
let mut writer = Vec::<u8>::new();
let mut json_writer = JsonStreamWriter::new(&mut writer);
let mut string_writer = json_writer.string_value_writer()?;
string_writer.write_all("text ".as_bytes())?;
string_writer.write_all(r#"with "quotes""#.as_bytes())?;
// Important: Must explicitly indicate that value is finished
string_writer.finish_value()?;
json_writer.finish_document()?;
let json = String::from_utf8(writer)?;
assert_eq!(json, r#""text with \"quotes\"""#);
§Writer errors
Writing invalid UTF-8 data to the writer will cause a std::io::Error
.
The error behavior of the string writer differs from the guarantees made by Write
:
- if an error is returned there are no guarantees about if or how many bytes have been written
- if an error occurs, processing should be aborted, regardless of the kind of the error; trying to use the string writer or the underlying JSON writer afterwards will lead to unspecified behavior
§Panics
Panics when called on a JSON writer which currently expects a member name, or
when called after the top-level value has already been written and multiple top-level
values are not enabled in the WriterSettings
. Both cases indicate incorrect
usage by the user.
sourcefn number_value_from_string(
&mut self,
value: &str
) -> Result<(), JsonNumberError>
fn number_value_from_string( &mut self, value: &str ) -> Result<(), JsonNumberError>
Writes the string representation of a JSON number value
This method is mainly intended for custom number implementations or situations
where the exact format of the JSON number is important. In all other cases either
number_value
or fp_number_value
should be used.
§Examples
let mut writer = Vec::<u8>::new();
let mut json_writer = JsonStreamWriter::new(&mut writer);
json_writer.number_value_from_string("123.0e10")?;
json_writer.finish_document()?;
let json = String::from_utf8(writer)?;
assert_eq!(json, "123.0e10");
§Errors
Returns a JsonNumberError::InvalidNumber
when the provided string is not a valid
JSON number. Non-finite floating point numbers such as NaN
or Infinity
are not
allowed by JSON and have to be written as JSON string value with string_value
.
§Panics
Panics when called on a JSON writer which currently expects a member name, or
when called after the top-level value has already been written and multiple top-level
values are not enabled in the WriterSettings
. Both cases indicate incorrect
usage by the user.
sourcefn number_value<N: FiniteNumber>(&mut self, value: N) -> Result<(), Error>
fn number_value<N: FiniteNumber>(&mut self, value: N) -> Result<(), Error>
Writes a finite JSON number value
This method supports all standard primitive integral number types, such as u32
.
To write a floating point number use fp_number_value
, to write a number in a
specific format use number_value_from_string
.
§Examples
let mut writer = Vec::<u8>::new();
let mut json_writer = JsonStreamWriter::new(&mut writer);
json_writer.number_value(123)?;
json_writer.finish_document()?;
let json = String::from_utf8(writer)?;
assert_eq!(json, "123");
§Panics
Panics when called on a JSON writer which currently expects a member name, or
when called after the top-level value has already been written and multiple top-level
values are not enabled in the WriterSettings
. Both cases indicate incorrect
usage by the user.
sourcefn fp_number_value<N: FloatingPointNumber>(
&mut self,
value: N
) -> Result<(), JsonNumberError>
fn fp_number_value<N: FloatingPointNumber>( &mut self, value: N ) -> Result<(), JsonNumberError>
Writes a floating point JSON number value
This method supports the standard floating point number types f32
and f64
.
To write an integral number value use number_value
, to write a number in a
specific format use number_value_from_string
.
The number is converted to a JSON number by calling to_string
on it.
§Examples
let mut writer = Vec::<u8>::new();
let mut json_writer = JsonStreamWriter::new(&mut writer);
json_writer.fp_number_value(4.5)?;
json_writer.finish_document()?;
let json = String::from_utf8(writer)?;
assert_eq!(json, "4.5");
§Errors
Returns a JsonNumberError::InvalidNumber
when the provided number is non-finite.
Non-finite floating point numbers such as NaN
or Infinity
are not
allowed by JSON and have to be written as JSON string value with string_value
.
§Panics
Panics when called on a JSON writer which currently expects a member name, or
when called after the top-level value has already been written and multiple top-level
values are not enabled in the WriterSettings
. Both cases indicate incorrect
usage by the user.
sourcefn serialize_value<S: Serialize>(
&mut self,
value: &S
) -> Result<(), SerializerError>
Available on crate feature serde
only.
fn serialize_value<S: Serialize>( &mut self, value: &S ) -> Result<(), SerializerError>
serde
only.Serializes a Serde Serialize
as next value
This method is part of the optional Serde integration feature, see the
serde
module of this crate for more information.
If it is not possible to directly serialize a value in place, instead of using
this method a JsonWriterSerializer
can be constructed and serialization can be performed using it later on. However,
this should only be rarely necessary.
§Examples
// In this example JSON bytes are stored in a Vec;
// normally they would be written to a file or network connection
let mut writer = Vec::<u8>::new();
let mut json_writer = JsonStreamWriter::new(&mut writer);
// Start writing the enclosing data using the regular JsonWriter methods
json_writer.begin_object()?;
json_writer.name("outer")?;
#[derive(Serialize)]
struct MyStruct {
text: String,
number: u64,
}
let value = MyStruct {
text: "some text".to_owned(),
number: 5,
};
// Serialize the value as next JSON value
json_writer.serialize_value(&value)?;
// Write the remainder of the enclosing data
json_writer.end_object()?;
// Ensures that the JSON document is complete and flushes the buffer
json_writer.finish_document()?;
let json = String::from_utf8(writer)?;
assert_eq!(
json,
r#"{"outer":{"text":"some text","number":5}}"#
);
§Errors
Errors can occur when either this JSON writer or the Serialize
encounters an
error. In which situations this can happen depends on the Serialize
implementation.
§Panics
Panics when called on a JSON writer which currently expects a member name, or
when called after the top-level value has already been written and multiple top-level
values are not enabled in the WriterSettings
. Both cases indicate incorrect
usage by the user.
sourcefn finish_document(self) -> Result<(), Error>
fn finish_document(self) -> Result<(), Error>
Verifies that the JSON document is complete and flushes the buffer
This method must be called explicitly. Dropping the JSON writer will not automatically flush the buffer.
Important: It is expected that there is always at least one top-level value in a JSON document, so calling this method without having written a value yet will panic, see “Panics” section below.
§Panics
Panics when called on a JSON writer which has not written any top-level yet, or when called while the top-level value has not been fully written yet. Both cases indicate incorrect usage by the user.