Protobuf消息到字节的JSON转换字段将字符串转换为base64? [英] Protobuf Message to JSON conversion of bytes field converts string to base64?

查看:238
本文介绍了Protobuf消息到字节的JSON转换字段将字符串转换为base64?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的原始文件:

I have a proto file like below:

syntax = "proto2";
package user;

message user_message {
    required bytes   username = 1;
    optional string   phonenum  = 2;
    optional string   password  = 3;
}

当我收到消息时,该消息从发件人序列化为字符串.

When I receive the message, that is serialised as a String from the sender.

我尝试将其转换为JSON对象:

This I try to convert to a JSON object:

base_msg = msg_periodic_pb2.m_apps_message()
base_msg.ParseFromString(message)
base_msg = json_format.MessageToJson(base_msg)

当我打印base_msg时,将消息转换为JSON后,用户名将转换为base64字符串.如何避免这种情况?

When I print the base_msg, after converting the message to JSON the username gets converted to a base64 string. How can I avoid this?

推荐答案

检查此评论.

这种行为实际上是可以预期的,因为字节字段(与字符串字段不同)可以包含非UTF8二进制数据,并且由于不能直接用JSON表示,因此我们必须对其进行base64编码."

"This behavior is actually to be expected, because bytes fields (unlike string fields) can contain non-UTF8 binary data, and since that cannot be directly represented in JSON, we have to base64-encode it."

因此,如果您真的想要字符串.您不能将protobuf类型设置为字节.

So, if you really want to have strings. You cannot have the protobuf type as bytes.

这篇关于Protobuf消息到字节的JSON转换字段将字符串转换为base64?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆