From 4cfc04799dd06e6cc6921d030e5636ceda525fcc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89lo=C3=AFs?= <elois@ifee.fr> Date: Sun, 11 Nov 2018 17:34:45 +0100 Subject: [PATCH] [ref] all: add trait TojsonObject --- Cargo.lock | 1 + documents/Cargo.toml | 1 + documents/src/lib.rs | 18 ++++++++++++++++++ 3 files changed, 20 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index c2f1fcc3..801e0864 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 3b9d92de..042065c0 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 0c5e8317..586f5d41 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())?) + } +} -- GitLab