Add from_arbitrary_json to AnyBase

This commit is contained in:
asonix 2020-11-25 10:11:10 -06:00
parent 9d34cb6e1c
commit feb42ee3ed
4 changed files with 28 additions and 2 deletions

View file

@ -1,5 +1,8 @@
# Unreleased # Unreleased
# 0.7.0-alpha.8
- Add `from_arbitrary_json` to AnyBase
# 0.7.0-alpha.7 # 0.7.0-alpha.7
- implement Extends for Base - implement Extends for Base

View file

@ -1,7 +1,7 @@
[package] [package]
name = "activitystreams" name = "activitystreams"
description = "A set of core types and traits for activitystreams data" description = "A set of core types and traits for activitystreams data"
version = "0.7.0-alpha.7" version = "0.7.0-alpha.8"
license = "GPL-3.0" license = "GPL-3.0"
authors = ["asonix <asonix@asonix.dog>"] authors = ["asonix <asonix@asonix.dog>"]
repository = "https://git.asonix.dog/Aardwolf/activitystreams" repository = "https://git.asonix.dog/Aardwolf/activitystreams"

View file

@ -11,7 +11,7 @@ _A set of Traits and Types that make up the ActivityStreams and ActivityPub spec
First, add ActivityStreams to your dependencies First, add ActivityStreams to your dependencies
```toml ```toml
[dependencies] [dependencies]
activitystreams = "0.7.0-alpha.6" activitystreams = "0.7.0-alpha.8"
``` ```
### Types ### Types

View file

@ -1097,6 +1097,29 @@ impl<Kind> Base<Kind> {
} }
impl AnyBase { impl AnyBase {
/// Convert arbitrary json into an AnyBase
///
/// This is provided so that strangely-shaped objects, specifically in context fields, can be
/// easily added into a structure, but otherwise probably shouldn't be used.
///
/// ```rust
/// # fn main() -> Result<(), anyhow::Error> {
/// # use activitystreams::base::AnyBase;
/// let any_base = AnyBase::from_arbitrary_json(serde_json::json!({
/// "key": "value"
/// }))?;
/// # Ok(())
/// # }
/// ```
pub fn from_arbitrary_json<T>(serializable: T) -> Result<Self, serde_json::Error>
where
T: serde::Serialize,
{
let value = serde_json::to_value(serializable)?;
let base: Base<serde_json::Value> = serde_json::from_value(value)?;
Ok(base.into())
}
/// Convert any type that is extended from `Base<Kind>` into an AnyBase for storing /// Convert any type that is extended from `Base<Kind>` into an AnyBase for storing
/// ///
/// ```rust /// ```rust