Skip to main content

typespec/
json.rs

1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT License.
3
4//! JSON serialization functions.
5use crate::error::Result;
6use bytes::Bytes;
7use serde::{de::DeserializeOwned, Serialize};
8
9/// Serialize a type to JSON.
10pub fn to_json<T>(value: &T) -> Result<Bytes>
11where
12    T: ?Sized + Serialize,
13{
14    Ok(Bytes::from(serde_json::to_vec(value)?))
15}
16
17/// Reads the JSON from bytes.
18pub fn from_json<S, T>(body: S) -> Result<T>
19where
20    S: AsRef<[u8]>,
21    T: DeserializeOwned,
22{
23    serde_json::from_slice(body.as_ref()).map_err(Into::into)
24}