CoplayDev/unity-mcp · error · JsonSerializationException

Cannot deserialize Vector2 from {token.Type}: '{token}'

Error message

Cannot deserialize Vector2 from {token.Type}: '{token}'

What it means

Thrown by Vector2Converter.ReadJson when the JSON token is neither a JArray with count >= 2 nor a JObject. Vector2 accepts [x, y] array form or {"x":..,"y":..} object form. Any other token type or an array with fewer than 2 elements is rejected.

Source

Thrown at MCPForUnity/Runtime/Serialization/UnityTypeConverters.cs:59

    public class Vector2Converter : JsonConverter<Vector2>
    {
        public override void WriteJson(JsonWriter writer, Vector2 value, JsonSerializer serializer)
        {
            writer.WriteStartObject();
            writer.WritePropertyName("x");
            writer.WriteValue(value.x);
            writer.WritePropertyName("y");
            writer.WriteValue(value.y);
            writer.WriteEndObject();
        }

        public override Vector2 ReadJson(JsonReader reader, Type objectType, Vector2 existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            JToken token = JToken.Load(reader);
            if (token is JArray arr && arr.Count >= 2)
                return new Vector2((float)arr[0], (float)arr[1]);
            if (token is not JObject jo)
                throw new JsonSerializationException($"Cannot deserialize Vector2 from {token.Type}: '{token}'");
            return new Vector2(
                (float)jo["x"],
                (float)jo["y"]
            );
        }
    }

    public class QuaternionConverter : JsonConverter<Quaternion>
    {
        public override void WriteJson(JsonWriter writer, Quaternion value, JsonSerializer serializer)
        {
            writer.WriteStartObject();
            writer.WritePropertyName("x");
            writer.WriteValue(value.x);
            writer.WritePropertyName("y");
            writer.WriteValue(value.y);
            writer.WritePropertyName("z");
            writer.WriteValue(value.z);

View on GitHub (pinned to c21bf496bc)

Solutions

  1. Send Vector2 as [x, y] array: "scale": [1.0, 1.0].
  2. Or send as object: "scale": {"x": 1.0, "y": 1.0}.
  3. Ensure arrays have exactly 2 numeric elements.
  4. Do not pass scalar or string values for vector fields.

Example fix

// before
params = {"scale": "1,1"}
// after
params = {"scale": [1.0, 1.0]}
Defensive patterns

Strategy: type-guard

Validate before calling

def is_valid_vector2(val) -> bool:
    if isinstance(val, (list, tuple)) and len(val) >= 2:
        return all(isinstance(v, (int, float)) for v in val[:2])
    if isinstance(val, dict):
        return all(k in val for k in ('x', 'y'))
    return False

Type guard

function isVector2(val: unknown): val is number[] | {x:number;y:number} {
  if (Array.isArray(val) && val.length >= 2)
    return val.slice(0, 2).every(v => typeof v === 'number');
  if (val && typeof val === 'object' && 'x' in val && 'y' in val)
    return true;
  return false;
}

Try / catch

try
{
    var vec = serializer.Deserialize<Vector2>(reader);
}
catch (JsonSerializationException ex) when (ex.Message.Contains("Cannot deserialize Vector2"))
{
    return new ErrorResponse($"Vector2 must be [x,y] or {{x,y}}.");
}

Prevention

When it happens

Trigger: Deserializing a Vector2 field from JSON where the value is a scalar, string, boolean, or array with < 2 elements. Common when a 2D coordinate is sent as a single value or a comma-separated string.

Common situations: Client sends UV or 2D scale as a single number; AI outputs a string for a vector field; array with one element; type confusion between Vector2 and Vector3.

Related errors


AI-assisted analysis of CoplayDev/unity-mcp@c21bf496bc (2026-08-13). Data as JSON: /api/errors/5390964ac196801f. Report an issue: GitHub.