如何将protobuf类实例格式化为没有未知字段的json字符串?

时间:2018-01-15 08:54:54

标签: java json protocol-buffers

  

问题背景

我使用谷歌提供的这个库将protobuf类实例格式化为json字符串。

可用的api用法:JsonFormat.printToString(docInfo)

<dependency>
    <groupId>com.googlecode.protobuf-java-format</groupId>
    <artifactId>protobuf-java-format</artifactId>
    <version>1.2</version>
    <scope>compile</scope>
</dependency>

但我遇到了一个非常棘手的情况。

因为这个库会自动将protobuf类实例的未知字段添加到json对象,然后它们将被解码为字符串文本作为相应的值。

因为我们不知道未知字段的类型,所以简单的字符串文本编码方法可能会触发非常严重的结果!!!

{"code": 1,"msg": "","code1": 2, "4": [3]}

如此键“4”。

有人能告诉我如何将pb类实例格式化为没有未知字段的json文本字符串吗?

非常感谢。

1 个答案:

答案 0 :(得分:0)

JsonFormat的类com.googlecode.protobuf.format不会忽略未知字段。

一种解决方法是使用protobuf-java-format 1.3(或更高版本)并创建一个扩展JsonFormat并覆盖方法protected void print(Message message, JsonGenerator generator) throws IOException的类。

您可以使用下面的类(在Scala中)。

使用此类,您将通过调用printToString(message=<your_message>)获得以下json:

{"code": 1,"msg": "","code1": 2}

import com.google.protobuf.Message
import com.googlecode.protobuf.format.JsonFormat
import com.googlecode.protobuf.format.JsonFormat.JsonGenerator
import java.util.Iterator
/** A JsonFormat class that ignore unknown fields.
 *
 *  Example of use: You have a protobuf message, called message, and you want 
 *  to get the json presentation as string with ignoring unknown fields:
 *  val jsonFormatExtension: JsonFormatExtension = new JsonFormatExtension()
 *  val jsonStr: String = jsonFormatExtension.printToString(message=message)
 */
class JsonFormatExtension extends JsonFormat {
  override def print(message: Message, generator: JsonGenerator):Unit = {
    var iter = message.getAllFields().entrySet().iterator()
    while (iter.hasNext()) {
      var field = iter.next()
      printField(field.getKey(), field.getValue(), generator)
      if (iter.hasNext()) {
        generator.print(",")
      }
    }
    // disable printing unknown fields
    // if (message.getUnknownFields().asMap().size() > 0)
    //   generator.print(", ")
    // printUnknownFields(message.getUnknownFields(), generator)
  }
}
相关问题