oxygengine_core/assets/protocols/
json.rs1use crate::assets::protocol::{AssetLoadResult, AssetProtocol};
2use serde::de::DeserializeOwned;
3use serde_json::Value;
4use std::str::from_utf8;
5
6pub struct JsonAsset(Value);
7
8impl JsonAsset {
9 pub fn get(&self) -> &Value {
10 &self.0
11 }
12
13 pub fn deserialize<T>(&self) -> Result<T, String>
14 where
15 T: DeserializeOwned,
16 {
17 match serde_json::from_value(self.0.clone()) {
18 Ok(result) => Ok(result),
19 Err(error) => Err(error.to_string()),
20 }
21 }
22}
23
24pub struct JsonAssetProtocol;
25
26impl AssetProtocol for JsonAssetProtocol {
27 fn name(&self) -> &str {
28 "json"
29 }
30
31 fn on_load(&mut self, data: Vec<u8>) -> AssetLoadResult {
32 let data = from_utf8(&data).unwrap();
33 match serde_json::from_str(data) {
34 Ok(value) => AssetLoadResult::Data(Box::new(JsonAsset(value))),
35 Err(error) => AssetLoadResult::Error(format!("Error loading JSON asset: {:?}", error)),
36 }
37 }
38}