Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with null values when serializing arrays with protobuf-net?

The following statement fails with NullReferenceException:

TypeModel.Create().DeepClone(new string[1]);

Examining the source code reveals that the exception is thrown on purpose, implying that null values in an array violate the protocol buffers spec (makes sense, null is not a repetition of any value).

OK, the spec is right, but what should we do if there is still a null value in a collection? Is there a solution, besides making sure no null values ever creep into our collections ?

Thanks.

like image 475
mark Avatar asked Sep 07 '11 09:09

mark


2 Answers

See this:

http://code.google.com/p/protobuf-net/issues/detail?id=217

Citation of the relevant part:

Comment 4 by project member marc.gravell, Dec 14, 2011

I haven't documented that option yet (it was added as a specific request), but - at the moment you can only enable this via (for example):

RuntimeTypeModel.Default[typeof (YourType)][3].SupportNull = true;

where 3 is the field-number.

This should probably be available on the attribute model too...

Note to the user "will" - the deleter of my previous answer - I know this is not the best place, but I do not know of other way to message You and being simply quiet in such case is wrong: I am sorry about the "too short" answer on the first time, BUT wouldnt the editing be more constructive approach than sudden deletion? The link I provided still DID answer the problem, as also was evidenced by the comment... I only by chance found that You did delete it.

like image 184
Roland Pihlakas Avatar answered Dec 02 '22 23:12

Roland Pihlakas


It is a tricky one; at the wire level, a collection is simply a repeated tag - and each element represents an object. Quite simply, there is no way of directly expressing a null in the protobuf spec.

Now, I could get dirty and have some kind of dual tag for a collection-with-nulls, but - to be honest I think it would generally be better to use a null-looking non-null object (if you see what I mean). In the case of string, maybe "" would do (it depends on context, really).

I'm open to suggestions too, but... it would need to keep the limitations of the spec in mind.

like image 35
Marc Gravell Avatar answered Dec 02 '22 21:12

Marc Gravell