Skip to main content

FromJsonKey

Trait FromJsonKey 

Source
pub trait FromJsonKey<'de>: Sized {
    // Required method
    fn from_json_key(key: Cow<'de, str>) -> Result<Self, DecodeErrorKind>;
}
Expand description

A type usable as a JSON object key, for FromJson on maps.

§Examples

use std::{borrow::Cow, collections::BTreeMap};
use jsonx_lib::{DecodeErrorKind, FromJsonKey};

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
struct Lang(String);

impl<'de> FromJsonKey<'de> for Lang {
    fn from_json_key(key: Cow<'de, str>) -> Result<Self, DecodeErrorKind> {
        if key.len() == 2 { Ok(Lang(key.into_owned())) } else { Err(DecodeErrorKind::InvalidValue("a language code")) }
    }
}

let names: BTreeMap<Lang, String> = jsonx_lib::from_str(r#"{"en": "hello"}"#)?;
assert_eq!(names[&Lang("en".into())], "hello");
let err = jsonx_lib::from_str::<BTreeMap<Lang, String>>(r#"{"eng": "x"}"#).unwrap_err();
assert_eq!(err.pointer(), "/eng");

Required Methods§

Source

fn from_json_key(key: Cow<'de, str>) -> Result<Self, DecodeErrorKind>

Makes the key from its decoded text.

§Errors

The reason the text is not a valid key; the map reports it at the key, with the key in the path.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementations on Foreign Types§

Source§

impl<'de> FromJsonKey<'de> for &'de str

Source§

impl<'de> FromJsonKey<'de> for Box<str>

Source§

impl<'de> FromJsonKey<'de> for Cow<'de, str>

Source§

impl<'de> FromJsonKey<'de> for String

Implementors§