Skip to content

Instantly share code, notes, and snippets.

@ChristopherBiscardi
Created March 23, 2025 19:38
Show Gist options
  • Save ChristopherBiscardi/8036b80459805e277ab875afc19ce9da to your computer and use it in GitHub Desktop.
Save ChristopherBiscardi/8036b80459805e277ab875afc19ce9da to your computer and use it in GitHub Desktop.
Vec3 asymmetrical serialization/deserialization
use bevy::reflect::erased_serde::__private::serde::de::DeserializeSeed;
use bevy::{
prelude::*,
reflect::{
TypeRegistry,
serde::{ReflectDeserializer, ReflectSerializer},
},
};
use serde_json::Value;
#[derive(Reflect, Component)]
#[reflect(Component)]
struct LinearVelocity(Vec3);
fn main() {
let value = LinearVelocity(Vec3::splat(2.));
let mut type_registry = TypeRegistry::new();
// serialize
let serializer =
ReflectSerializer::new(&value, &type_registry);
let json_string =
serde_json::ser::to_string(&serializer).unwrap();
// verify string contents
assert_eq!(
json_string,
r#"{"test_components::LinearVelocity":{"x":2.0,"y":2.0,"z":2.0}}"#
);
let Ok(Value::Object(object)) =
serde_json::from_str(&json_string)
else {
panic!("parsing failed");
};
type_registry.register::<LinearVelocity>();
// deserialize
let reflect_deserializer =
ReflectDeserializer::new(&type_registry);
let reflect_value =
reflect_deserializer.deserialize(object).unwrap();
dbg!(reflect_value);
}
@ChristopherBiscardi
Copy link
Author

output in 0.15.3 and 0.16.0-rc.1

called `Result::unwrap()` on an `Err` value: Error("invalid type: map, expected a sequence of 3 f32 values", line: 0, column: 0)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment