How to serialize NetTopologySuite classes like Polygon using protocol buffer in C#?

143 Views Asked by At

I'm new to protocol buffers. I thought to use protobuf-net nuget to serialize / deserialize my City class. Polygon is a type from NetTopologySuite nuget.

[ProtoContract]
public class City
{
    [ProtoMember(1)]
    public Guid Id { get; set; }

    [ProtoMember(2)]
    public string Name { get; set; }

    [ProtoMember(3)]
    public int Population { get; set; }

    [ProtoMember(4)]
    public Polygon Area { get; set; } 
}

Of course, it can not serialize property Area. Do you have any suggestions how I can provide some custom serializer for Area or may be there is another way to serialize City class ? By using Google.Protobuf nuget?

1

There are 1 best solutions below

1
JonasH On

If you are using protobuf.net you could use surrogates:

var typeModel = RuntimeTypeModel.Create();
typeModel.Add(typeof(Polygon ), false).SetSurrogate(typeof(PolygonSurrogate));

...

[ProtoContract]
class PolygonSurrogate
{
   // Members

    public PolygonSurrogate(...){ ... }

    public static implicit operator Polygon (PolygonSurrogate dto) => new(...);
    public static implicit operator PolygonSurrogate(Polygon model) => new(...);
}

You then need to use that type model whenever you are serializing/deserializing. You need to write some code to do the actual conversion between the netTopologySuite and your surrogate classes.

For simpler types you can just specify properties to serialize, but I would guess that a Polygon is to complex for that approach.

But I would consider just doing the type conversion to a protobuf compatible type in your City class directly. That might be easier to read and understand than using a type model that defines conversions.