美文网首页
proto对象与Java对象的转换工具类

proto对象与Java对象的转换工具类

作者: 小胖学编程 | 来源:发表于2023-09-15 18:19 被阅读0次

背景:在使用grpc通信过程中,需要定义proto协议。proto协议会生成pb对象,为了不让pb对象侵入到业务代码,所以需要将pb对象转化成java对象。如何降低get、set的工作量?实现快速复制(深拷贝)?

1、pb与java对象转化

1.1 不能利用反射

首先我们不能简单的使用反射机制(无论是操作field字段,还是操作getter/setter方法)。因为pb方法生成的对象有以下特点:

  • ProtoBean不允许有null值,而Pojo允许有null值,从Pojo拷贝到Proto必然会有非空异常
  • BeanUtils 会按照方法名及getter/setter类型进行匹配,嵌套类型因为类型不匹配而无法正常拷贝
  • Map和List的Proto属性生成的Java会分别在属性名后增加Map和List,如果希望能够进行拷贝,则需要按照这个规则明明Projo的属性名
  • Enum类型不匹配无法进行拷贝,如果希望能够进行拷贝,可以尝试使用ProtoBean的Enum域的get**Value()方法,并据此命名Pojo属性名

1.2 通过序列化方式

引入依赖:

<!-- https://mvnrepository.com/artifact/com.google.protobuf/protobuf-java-util -->
<dependency>
    <groupId>com.google.protobuf</groupId>
    <artifactId>protobuf-java-util</artifactId>
    <version>3.7.1</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.googlecode.protobuf-java-format/protobuf-java-format -->
<dependency>
    <groupId>com.googlecode.protobuf-java-format</groupId>
    <artifactId>protobuf-java-format</artifactId>
    <version>1.4</version>
</dependency>

工具方法:

import java.io.IOException;

import com.google.gson.Gson;
import com.google.protobuf.Message;
import com.google.protobuf.util.JsonFormat;

/**
 * 相互转化的两个对象的getter和setter字段要完全的匹配。
 * 此外,对于ProtoBean中的enum和bytes,与POJO转化时遵循如下的规则:
 * <ol>
 *     <li>enum -> String</li>
 *     <li>bytes -> base64 String</li>
 * </ol>
 * @author Yang Guanrong
 * @date 2019/08/18 23:44
 */
public class ProtoBeanUtils {

    /**
     * 将ProtoBean对象转化为POJO对象
     *
     * @param destPojoClass 目标POJO对象的类类型
     * @param sourceMessage 含有数据的ProtoBean对象实例
     * @param <PojoType> 目标POJO对象的类类型范型
     * @return
     * @throws IOException
     */
    public static <PojoType> PojoType toPojoBean(Class<PojoType> destPojoClass, Message sourceMessage)
        throws IOException {
        if (destPojoClass == null) {
            throw new IllegalArgumentException
                ("No destination pojo class specified");
        }
        if (sourceMessage == null) {
            throw new IllegalArgumentException("No source message specified");
        }
        String json = JsonFormat.printer().print(sourceMessage);
        return new Gson().fromJson(json, destPojoClass);
    }

    /**
     * 将POJO对象转化为ProtoBean对象
     *
     * @param destBuilder 目标Message对象的Builder类
     * @param sourcePojoBean 含有数据的POJO对象
     * @return
     * @throws IOException
     */
    public static void toProtoBean(Message.Builder destBuilder, Object sourcePojoBean) throws IOException {
        if (destBuilder == null) {
            throw new IllegalArgumentException
                ("No destination message builder specified");
        }
        if (sourcePojoBean == null) {
            throw new IllegalArgumentException("No source pojo specified");
        }
        String json = new Gson().toJson(sourcePojoBean);
        JsonFormat.parser().merge(json, destBuilder);
    }
}

2、java对象快速生成proto协议

idea下载pojo to proto插件。插件地址

类文件-右键-PojoProto, 将简单Java类型转成proto message拷贝至剪贴板

详见--文章

3、 proto协议如何传递null?

引入代码
import "google/protobuf/wrappers.proto";

Wrappers 的目标是解决基本类型存在不为空的默认值的问题,比如 int32 的默认值是 0,当我解析出一个 0 的时候,无法确定是真的 0 还是这个字段不存在。要解决也很简单,因为复合类型中的 message 是存在「空」的,只要把空判断交给 message 类型就可以了。Wrappers 提供了所有基本类型的「包装」message。

如何使用:

import "google/protobuf/wrappers.proto";

message InfoResp {
  google.protobuf.UInt64Value biz_id = 1;
}

如何解析:

Long bizId=request.hasBizId()?request.getBizId().getValue():null;

详见【菜狗教程】Protobuf.02 - 定义 message

文章参考

Protobuf与POJO的相互转化 - 通过Json

相关文章

网友评论

      本文标题:proto对象与Java对象的转换工具类

      本文链接:https://www.haomeiwen.com/subject/cutbvdtx.html