diff --git a/Cargo.lock b/Cargo.lock index c2f1fcc32d489e5e2eb760d6d667bfe4faa9d75f..801e0864f7d4280911b83fc09235c1b93e77305a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -316,6 +316,7 @@ dependencies = [ "pretty_assertions 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.78 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_json 1.0.21 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] diff --git a/documents/Cargo.toml b/documents/Cargo.toml index 3b9d92dee54fb6299338a5f4938162edb2c3c2e1..042065c0a3fa54f60e1dbe7dada6e6ea8e4aaa3e 100644 --- a/documents/Cargo.toml +++ b/documents/Cargo.toml @@ -20,6 +20,7 @@ pest = "2.0" pest_derive = "2.0" serde = "1.0.*" serde_derive = "1.0.*" +serde_json = "1.0.*" [dev-dependencies] pretty_assertions = "0.5.1" diff --git a/documents/src/lib.rs b/documents/src/lib.rs index 0c5e831756a1dc76b8c3f1e1600896d6b5de6b56..586f5d41f7889685eae9de7f8846cfe15f5150e6 100644 --- a/documents/src/lib.rs +++ b/documents/src/lib.rs @@ -39,6 +39,7 @@ extern crate pretty_assertions; extern crate serde; #[macro_use] extern crate serde_derive; +extern crate serde_json; pub mod blockstamp; mod currencies_codes; @@ -50,6 +51,7 @@ use dup_crypto::hashs::Hash; use dup_crypto::keys::*; use pest::iterators::Pair; use pest::Parser; +use serde::Serialize; use std::cmp::Ordering; use std::fmt::{Debug, Display, Error, Formatter}; use std::io::Cursor; @@ -315,3 +317,19 @@ pub trait DocumentParser<S, D, E> { /// Parse a source and return a document or an error. fn parse(source: S) -> Result<D, E>; } + +/// Jsonify a document +pub trait ToJsonObject { + type JsonObject: Serialize; + /// Transforms an object into a json object + fn to_json_object(&self) -> Self::JsonObject; + + /// Convert to JSON String + fn to_json_string(&self) -> Result<String, serde_json::Error> { + Ok(serde_json::to_string(&self.to_json_object())?) + } + /// Convert to JSON String pretty + fn to_json_string_pretty(&self) -> Result<String, serde_json::Error> { + Ok(serde_json::to_string_pretty(&self.to_json_object())?) + } +}