Home > Software engineering >  How to serialize protobuf from json with auto ignoring unknown fields in c#?
How to serialize protobuf from json with auto ignoring unknown fields in c#?

Time:02-02

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!

CodePudding user response:

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.

  • Related