How to serialize null values in array?

Viewed 292

I am working with protobuf-net v3.0.101 on Windows platform and getting the below exception for null values in String array while serializing it using grpc protobuf-net:

I have defined my DataContract like this:

[DataContract]
public class StringArray
{
    [DataMember(Order = 1)]
    public string[] StrArray;
}

Here is my actual message which I am try to serialize:

var stringArray = new StringArray() { StrArray = new string[] { "1", "2", null, "3" } };

And, this is how I am calling Serializer:

method.RequestMarshaller.ContextualSerializer(request, transmitPayload);

Here is the exception :

FAIL: Error: Unhandled exception in required test method. An element of type System.String was null; this might be as contents in a list/array. (System.NullReferenceException: An element of type System.String was null; this might be as contents in a list/array
   at ProtoBuf.Internal.ThrowHelper.ThrowNullRepeatedContents[T]()
   at ProtoBuf.Serializers.RepeatedSerializer`2.Write[TEnumerator](State& state, Int32 fieldNumber, SerializerFeatures category, WireType wireType, TEnumerator& values, ISerializer`1 serializer)
   at ProtoBuf.Serializers.VectorSerializer`1.Write(State& state, Int32 fieldNumber, SerializerFeatures category, WireType wireType, T[] values, ISerializer`1 serializer)
   at ProtoBuf.Serializers.RepeatedSerializer`2.WriteRepeated(State& state, Int32 fieldNumber, SerializerFeatures features, TCollection values, ISerializer`1 serializer)
   at proto_29(State& , StringArray )
   at ProtoBuf.ProtoWriter.State.SerializeRoot[T](T value, ISerializer`1 serializer)
   at ProtoBuf.MeasureState`1..ctor(TypeModel model, T& value, Object userState, Int64 abortAfter)
   at ProtoBuf.Meta.TypeModel.Measure[T](T value, Object userState, Int64 abortAfter)
   at ProtoBuf.Meta.TypeModel.ProtoBuf.IMeasuredProtoOutput<System.Buffers.IBufferWriter<System.Byte>>.Measure[T](T value, Object userState)
   at ProtoBuf.Grpc.Configuration.ProtoBufMarshallerFactory.ContextualSerialize[T](T value, SerializationContext context)
1 Answers

The problem here is: the underlying protobuf format has no concept of null. There is simply no way for me to encode that in an array, in an obvious way.

In V2 we did something whereby all array elements were (with this feature enabled) wrapped in an extra layer to allow us to interpret null values, but this takes more space on the wire, is not an in-place silent replacement, and isn't obvious to interpret. I haven't yet re-added that in V3, but we could do if it was highly needed. However, a lazy way of doing this today would be to serialize Foo[] where Foo is a type that has a string as the only member, field 1. It could be a value-type - possibly even a readonly struct record with a single field.

Related