use crate::config::{Config, SerializeMode};
use crate::error::StamError;
use crate::file::*;
use crate::types::*;
pub trait ToJson
where
Self: TypeInfo + serde::Serialize,
{
fn to_json_writer<W>(&self, writer: W, compact: bool) -> Result<(), StamError>
where
W: std::io::Write,
{
match compact {
false => serde_json::to_writer_pretty(writer, &self).map_err(|e| {
StamError::SerializationError(format!(
"Writing {} to file: {}",
Self::typeinfo(),
e
))
}),
true => serde_json::to_writer(writer, &self).map_err(|e| {
StamError::SerializationError(format!(
"Writing {} to file: {}",
Self::typeinfo(),
e
))
}),
}
}
fn to_json_file(&self, filename: &str, config: &Config) -> Result<(), StamError> {
debug(config, || {
format!("{}.to_file: filename={:?}", Self::typeinfo(), filename)
});
if let Type::TextResource | Type::AnnotationDataSet = Self::typeinfo() {
config.set_serialize_mode(SerializeMode::NoInclude); }
let compact = match config.dataformat {
DataFormat::Json { compact } => compact,
_ => {
if let Type::AnnotationStore = Self::typeinfo() {
return Err(StamError::SerializationError(format!(
"Unable to serialize to JSON for {} (filename {}) when config dataformat is set to {}",
Self::typeinfo(),
filename,
config.dataformat
)));
} else {
false
}
}
};
let writer = open_file_writer(filename, &config)?;
let result = self.to_json_writer(writer, compact);
if let Type::TextResource | Type::AnnotationDataSet = Self::typeinfo() {
config.set_serialize_mode(SerializeMode::AllowInclude); }
result
}
fn to_json_string(&self, config: &Config) -> Result<String, StamError> {
if let Type::TextResource | Type::AnnotationDataSet = Self::typeinfo() {
config.set_serialize_mode(SerializeMode::NoInclude); }
let result = match config.dataformat {
DataFormat::Json { compact: false } => {
serde_json::to_string_pretty(&self).map_err(|e| {
StamError::SerializationError(format!(
"Writing {} to string: {}",
Self::typeinfo(),
e
))
})
}
DataFormat::Json { compact: true } => serde_json::to_string(&self).map_err(|e| {
StamError::SerializationError(format!(
"Writing {} to string: {}",
Self::typeinfo(),
e
))
}),
_ => Err(StamError::SerializationError(format!(
"Unable to serialize to JSON for {} when config dataformat is set to {}",
Self::typeinfo(),
config.dataformat
))),
};
if let Type::TextResource | Type::AnnotationDataSet = Self::typeinfo() {
config.set_serialize_mode(SerializeMode::AllowInclude); }
result
}
}
pub trait FromJson<'a>
where
Self: TypeInfo + serde::Deserialize<'a>,
{
fn from_json_file(filename: &str, config: Config) -> Result<Self, StamError>;
fn from_json_str(string: &str, config: Config) -> Result<Self, StamError>;
}