Search code examples
jsonserializationmultidimensional-arrayservicestackservicestack-text

Serializing Multidimensional array to JSON with ServiceStack


Returning the following object excludes the property "coordinates" from the JSON. What am I doing wrong?

[Route("/GeozonePolygon/{ZoneType}")]
public class RequestGeozonePolygon{
    public int ZoneType { get; set; }
}

public class ResponseGeozonePolygon{
    public FeatureCollection Result { get; set; }
    public ResponseStatus ResponseStatus { get; set; }
}

public class GeozonePolygon : Service {
    public ResponseGeozonePolygon Any(RequestGeozonePolygon request){
        return new ResponseGeozonePolygon() { Result = (new DAL.GeoZone()).GetZoneGeoJsonByType(request.ZoneType) };
    }
}

These are the involved types:

public class Geometry {
    public string type {
        get { return GetType().Name; }
    }
}
public class Feature {
    public string type {
        get { return GetType().Name; }
    }

    public Geometry geometry { get; set; }
    public object properties { get; set; }
}
public class FeatureCollection {
    public string type {
        get { return GetType().Name; }
    }
    public Feature[] features { get; set; }
}
public class MultiPolygon : Geometry {
    public double[][][][] coordinates { get; set; }
}

FeatureCollection property geometry contains a MultiPolygon object.

Thanks in advance!


Solution

  • You are serializing only the properties of the Geometry object, even though the actual object is a MultiPolygon. As explained by Mythz,

    As there is no concept of 'type info' in the JSON spec, in order for inheritance to work in JSON Serializers they need to emit proprietary extensions to the JSON wireformat to include this type info - which now couples your JSON payload to a specific JSON serializer implementation.

    To enable support for polymorphic Geometry objects in Servicestack.text, add a type specific config setting to add 'type info' to the output. i.e.:

    JsConfig<Geometry>.ExcludeTypeInfo = false;
    

    (may also require adding an interface. See the tests for Polymorphic List serialization. and tests for Polymorphic Instance serialization. for examples)

    If you are loath to expose type info in your json, you can use custom serializers as an alternative solution.