Not able to serialize Object type

54 views
Skip to first unread message

Nihar Mishra

unread,
Oct 23, 2017, 3:07:36 AM10/23/17
to Protocol Buffers

Hi,

I have below class which is generated from .net client.
When i try to save in redis cache, i get the "Not able to serialize Object type" error.
Please help me how to resolve it. 

  public partial class AttributeValueType
    {
        [DataMember]
        private object itemField;


        [System.Xml.Serialization.XmlElementAttribute("IntValue", typeof(int))]
        [System.Xml.Serialization.XmlElementAttribute("StringValue", typeof(string))]
        [System.Xml.Serialization.XmlElementAttribute("dateValue", typeof(System.DateTime), DataType = "date")]
        [System.Xml.Serialization.XmlElementAttribute("doubleValue", typeof(double))]
        public object Item
        {
            get { return this.itemField; }
            set { this.itemField = value; }
        }
    }

Marc Gravell

unread,
Oct 23, 2017, 3:19:26 AM10/23/17
to Nihar Mishra, Protocol Buffers
 I'm assuming this is protobuf-net; the message is right : the library can't work with "object itemField". Perhaps the best thing would be to treat this like a "oneof" (in .proto terms) and have an accessor per possible type. For example:

    [ProtoMember(n)]
    private int ValueInt32 {
        get => (int)itemField;
        set => itemField = value;
    }
    private bool ShouldSerializeValueInt32() => itemField is int;

(with a different "n" per possible type)

The "ShouldSerialize..." pattern is a .net idiom supported by protobuf-net that provides memberwise conditional serialization.



--
You received this message because you are subscribed to the Google Groups "Protocol Buffers" group.
To unsubscribe from this group and stop receiving emails from it, send an email to protobuf+unsubscribe@googlegroups.com.
To post to this group, send email to prot...@googlegroups.com.
Visit this group at https://groups.google.com/group/protobuf.
For more options, visit https://groups.google.com/d/optout.

Marc Gravell

unread,
Oct 23, 2017, 4:48:33 AM10/23/17
to Nihar Mishra, Protocol Buffers
Yes, something like that; example: https://pastebin.com/CUvWz00L

On 23 October 2017 at 09:38, Nihar Mishra <itnm...@gmail.com> wrote:
Hi Marc,
Thanks a lot. Yes this is protobuf-net.
Still i don't get how to modify AttributeValueType class.

Do you mean that i should write 4 protomembers for the 4 types?

best Regards,
Nihar




--
Regards,

Marc

Marc Gravell

unread,
Oct 23, 2017, 4:56:54 AM10/23/17
to Nihar Mishra, Protocol Buffers
For completeness (mostly in case someone finds this via search in the future), if you were using .proto schema-based generation, "oneof" is your friend: https://protogen.marcgravell.com/#g01989f8da1f4ce8ab358756115478c37 (click "Generate" once the gist has loaded)
--
Regards,

Marc
Reply all
Reply to author
Forward
0 new messages