Search code examples
c#jsonserializationprotocol-buffersproto3

How to serialize protobuf from json with auto ignoring unknown fields in c#?


For example, I have a proto like this:

message ProtoType
{
    string field1 = 1;
    strin field2 = 2;
}

And I have a json deserialized from a newer version of this proto:

{
  "field1": "111",
  "field2": "222",
  "testField": "test"
}

I use this to serialize protobuf from json:

JsonParser.Default.Parse<ProtoType>(protojson);

However, if my json has some fields that don't exist in proto (like the testField below), it will throw an exception:

InvalidProtocolBufferException: Unknown field: testField

I wonder if there's a way to get a ProtoType instance which can automatically ignore unknown fields.

Thanks a lot!


Solution

  • You will need to use the class JsonParser.Setting and use the function WithIgnoreUnknownFields. So you will have something like this:

    var settings = JsonParser.Settings.Default.WithIgnoreUnknownFields(true);
    var t = new JsonParser(settings).Parse<Test.ProtoType>(protojson);
    

    Furthermore, the documentation doesn't seem to be covering that. I recommend that you check the JsonParser source code and search for the Settings class to get all the functions you can use.

    Edit

    For completeness, there is a copy of the C# documentation managed by the Google cloud team and this one is up-to-date.