简体   繁体   中英

Protobuf-net deserialize string field to c# guid

In a simplified scenario, assume we have a custom c# type which contains a guid field and the corresponding proto type is,

message HelloReply {
  string message = 1;
  string guid_id = 2; // this is defined GUID in corresponding c# type
  repeated string names = 3;
  map<string, double> prices = 4;
}

When I try to deserialize this proto to c# type, I get exception stating 'Invalid wire-type' and a link to explanation which is not helpful to me. Is there a work around for this or am I overlooking something ?

In protobuf-net v3, this changes; there is now a concept called CompatibilityLevel , that works for this scenario; if a Guid member or containing type has CompatibilityLevel of 300 or more, then it is treated as a string . This topic is discussed in depth here: https://github.com/protobuf-net/protobuf-net/blob/main/docs/compatibilitylevel.md

Protobuf-net has opinions on guids. Opinions that were forged back in the depth of time, and that I now regret, but which are hard to revert without breaking people. If I was writing this today with hindsight, yes: it would probably just serialize as a string. But: that isn't what it expects today!

Frankly I'd hack around it with a shadow property. So instead of

[ProtoMember(42)]
public Guid Foo {get;set;}

You could use:

public Guid Foo {get;set;}
[ProtoMember(42)]
private string FooSerialized {
    get => Foo.ToString(); // your choice of formatting
    set => Foo = Guid.Parse(value);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM