John
John

Reputation: 23

Serialize Array of Vector2 with Json.NET

I am trying to use Json.NET on Unity to serialize a class.
The class Polygon contains an Array of Vector2 but i only want to serialize the x and y variables of Vector2 class, that's why I'm using the JsonConverter attribute.

Sample class:

public class Polygon
{
    public int count { get; set; }

    [JsonConverter(typeof(Vector2Converter[]))]
    public Vector2[] points { get; set; }
}

It gives me this error at runtime:

MissingMethodException: Method not found: 'Default constructor not found...ctor() of JsonDotNet.Extras.CustomConverters.Vector2Converter[]

Anyone have any suggestions?

Upvotes: 2

Views: 4125

Answers (1)

Brian Rogers
Brian Rogers

Reputation: 129797

The [JsonConverter] attribute takes the type of a converter, not the type of an array of converters. If your converter is designed to handle the serialization of the entire array, then you need to specify it like this:

    [JsonConverter(typeof(Vector2Converter))]
    public Vector2[] points { get; set; }

If your converter is designed to serialize the individual items in the array, you need to use this syntax instead:

    [JsonProperty(ItemConverterType=typeof(Vector2Converter))]
    public Vector2[] points { get; set; }

Upvotes: 2

Related Questions