简体   繁体   中英

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

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.

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 (eg 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

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