Get only one field in protocol buffer without deserializing whole object in java

Viewed 392

I have POJO that serialized with protobuf. This object has many fields. I want to check one field. Is it possible to deserialize only one filed without deserializing the whole object in Java? I think it is probable in Python.

1 Answers

Yes, it is possible.

In case you are comfortable with Scala, the usage of the library is explained within the README.

  • Also, the tests might give you a good idea of how to use the API.

In case you need Java native solution, you can easily implement it yourself. For details, see the staticExtract method.

Here is a Scala snippet of the implementation (any decent IDE should automatically convert this to Java while pasting):

  def staticExtract[T](codedInputStream: CodedInputStream, fieldDescriptor: FieldDescriptor, extractionMethod: CodedInputStream => T): T = {
    while (!codedInputStream.isAtEnd) {
      if (WireFormat.getTagFieldNumber(codedInputStream.readTag()) == fieldDescriptor.getNumber) {
        return extractionMethod.apply(codedInputStream)
      } else codedInputStream.skipField(codedInputStream.getLastTag)
    }
    fieldDescriptor.getDefaultValue.asInstanceOf[T]
  }
  • all it does, is it iterates over the input stream until either:
    • the queried field is found
      • then the provided extraction method is applied upon the current stream state (e.g. CodedInputStream.readBool())
      • it is important to note, that the tag read by the CodedInputStream contains both the fieldNumber and the wireType (as explained here), so you have to first extract the fieldNumber in order to match it with the FieldDescriptor's number
    • the end is reached
      • in which case, the default value is returned
Related