Hi,
I’m trying to use the com.unity.serialization package to deserialize a json coming from an external source (simplified version):
{
"filename": "body.obj",
"local": {
"origin": [0.0, 1.0, 0.0],
"rotation_xyz": [315.0, 0.0, 0.0],
}
}
As you can see, it uses arrays to represent Vector3, instead of what the com.unity.serialization expect by default:
{
"filename": "body.obj",
"local": {
"origin": {
"x": 0.0,
"y": 1.0,
"z": 0.0
},
"rotation_xyz": {
"x": 315.0,
"y": 0.0,
"z": 0.0
}
}
}
So, I wrote a custom adapter and had to end with (still needs more exception checks for wrong formatted arrays):
class Vector3ArrayAdapter : IJsonAdapter<Vector3>
{
public Vector3 Deserialize(in JsonDeserializationContext<Vector3> context)
{
if (context.SerializedValue.Type == TokenType.Array) {
SerializedArrayView arrayView = context.SerializedValue.AsArrayView();
SerializedArrayView.Enumerator enumerator = arrayView.GetEnumerator();
enumerator.MoveNext();
float x = enumerator.Current.AsFloat();
enumerator.MoveNext();
float y = enumerator.Current.AsFloat();
enumerator.MoveNext();
float z = enumerator.Current.AsFloat();
return new Vector3(x, y, z);
}
return context.ContinueVisitation();
}
public void Serialize(in JsonSerializationContext<Vector3> context, Vector3 value)
{
using var objectScope = context.Writer.WriteArrayScope();
context.Writer.WriteValue(value.x);
context.Writer.WriteValue(value.y);
context.Writer.WriteValue(value.z);
}
}
It works, but the Deserialize method is ugly. As you can see, I have to use an SerializedArrayView.Enumerator and couldn’t use the [] operator. I’d like to be able to write:
public Vector3 Deserialize(in JsonDeserializationContext<Vector3> context)
{
if (context.SerializedValue.Type == TokenType.Array) {
SerializedArrayView arrayView = context.SerializedValue.AsArrayView();
return new Vector3(arrayView[0].AsFloat(), arrayView[1].AsFloat(), arrayView[2].AsFloat());
}
return context.ContinueVisitation();
}
In Unity’s package code, there is everything I need, but they arn’t public… Visual Studio say there is 0 references to those methods, so unless it’s made public, they are useless. See line 135 of SerializedArrayView.cs:
Is it done on purpose or just someone forget to make this public? Or did I miss something?
Edit: just saw when posting that the [] method is using the enumerator, so switching to [] will be less perfromant because of the use of a new enumerator for each index instead of reusing it as I did.
