9

Kotlin/Java 列表Protobuf序列化

 3 years ago
source link: https://jiajunhuang.com/articles/2021_01_13-kotlin_protobuf_serialization.md.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Kotlin/Java 列表Protobuf序列化

本来想保存一些Protobuf生成的类的实例到本地,方法自然就是把一个列表的数据序列化成bytes,然后存起来。不过 搞了半天都没办法,于是就自己整了一个 “poor man’s serialization for list of protobuf object”。

方法很简单,首先遍历 List<Cashapp.Bookkeeping> ,依次调用 toByteArray() 得到 []byte,然后进行 Base64编码,就得到了字符串。然后把多个字符串用某个字符串拼接,例如 ; 或者 \n,最后写入,如果是写文件的话, 也可以直接bytes写入。

那么反序列化,就按着上面步骤,反过来执行即可。

private fun saveBKList(bkList: List<Cashapp.Bookkeeping>) {
    val encodedBKList = ArrayList<String>()

    for (i in bkList) {
        encodedBKList.add(Base64.encodeToString(i.toByteArray(), Base64.DEFAULT))
    }

    kv.encode("latest_bk_list", encodedBKList.joinToString("\n"))
}

不过最后我还是没有执行这一步,因为虽然把列表缓存下来了,打开App时可以直接显示最近一次的列表,但是此时用户还没登录, 感觉怪怪的。


微信公众号
关注公众号,获得及时更新

nomad简明教程

Linux下当笔记本合上盖子之后只使用扩展显示器

Ubuntu 18.04 dhcp更换新IP

Python中的新式类(new style class)和老式类(old style class)

Python Requests 简明教程

密码技术简明教程(三):证书和TLS

密码技术简明教程(二):散列、消息认证码和数字签名

SEO学习笔记

密码技术简明教程(一):对称加密和非对称加密

Kubernetes 笔记

go mod 和 logrus 路径大小写的问题

Flask自动加载Blueprint

在KVM里安装Minikube

搞定面试中的系统设计题

Crontab + Sendmail实现定时任务并且通知




About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK