如何反序列化从Google protobuf用Java接收的字节?

时间:2017-03-02 14:26:36

标签: java json protocol-buffers zeromq

我正在尝试反序列化从ZeroMQ收到的google protobuf消息,并尝试使用下面的代码转换为JSON格式。但是在最终输出中,定义为字节的字段是不可读的。

  

(例如,"source_id": "\u0000PV\uff98t\uff9e")。

由于这是机器生成的数据,因此我们不会从源发送实际值。

InputStream is = new ByteArrayInputStream( message.getBytes() );
Schema.nb_event data = Schema.nb_event.parseFrom( is );
String jsonFormat = JsonFormat.printToString( data );

输出

{ "seq": 6479250, "timestamp": 1488461706,"op": "OP_UPDATE","topic_seq": 595736,"source_id": "\u0000PV\uff98t\uff9e","location": {"sta_eth_mac": {"addr": "xxxxxxx"},"sta_location_x": 879.11456,"sta_location_y": 945.0676,"error_level": 1220,"associated": true,"campus_id": "\uff9f\uff94\uffc7\uffa3\uffa2\b6\uffe3\uff92U\uff9f\uffdcN\'MT","building_id": "\uffee\u0016??X}5\u001a\uffaa\uffc4^\uffa0n\uffa4\ufffb\'","floor_id": "\uffd9/\"uF\uffdd3\uffdd\uff96\u0015\uff83~\u0005\uff8a(\uffd0","hashed_sta_eth_mac": "\u0013h\u0017\uffd0\uffef\uffc8\u001f\u0005V\u0010w?xxxxxx","loc_algorithm": "ALGORITHM_LOW_DENSITY","unit": "FEET"}}

==

{ "seq":          6479250,
  "timestamp": 1488461706,
  "op":                  "OP_UPDATE",
  "topic_seq":     595736,
  "source_id":           "\u0000PV\uff98t\uff9e",
  "location":          { "sta_eth_mac":          { "addr": "\uffc0\uffcc\ufff8P\uffee." },
                         "sta_location_x":    879.11456,
                         "sta_location_y":    945.0676,
                         "error_level":      1220,
                         "associated":            true,
                         "campus_id":            "\uff9f\uff94\uffc7\uffa3\uffa2\b6\uffe3\uff92U\uff9f\uffdcN\'MT",
                         "building_id":          "\uffee\u0016??X}5\u001a\uffaa\uffc4^\uffa0n\uffa4\ufffb\'",
                         "floor_id":             "\uffd9/\"uF\uffdd3\uffdd\uff96\u0015\uff83~\u0005\uff8a(\uffd0",
                         "hashed_sta_eth_mac":   "\u0013h\u0017\uffd0\uffef\uffc8\u001f\u0005V\u0010w?\uff88\uffa8\uffee\u000fm.\u0015\uffe9",
                         "loc_algorithm":        "ALGORITHM_LOW_DENSITY",
                         "unit":                 "FEET"
                         }
  }

所有不可读的字段都定义为 .proto 文件中的字节。
获取这些值是否还需要其他步骤? < / p>

    optional bytes building_id        = 10;
    optional bytes floor_id           = 11;
    optional bytes hashed_sta_eth_mac = 12;

1 个答案:

答案 0 :(得分:0)

JSON格式化程序com.googlecode.protobuf.format.JsonFormat以字节形式返回,但在将JSON格式化程序更改为com.google.protobuf.util.JsonFormat后,我能够获取所需格式的base64字符串。