ScalaでprotoをJSONにする
そもそもなんでわざわざprotoをJSONにしているのかというと
- 重いバッチがあって、その中で一部の処理が重い
- 「一部の処理」を別バッチに切り出して並列処理をする
- 元のバッチのジョブと切り出したバッチのジョブの間でオブジェクトをやりとりしたい =>JSONにシリアライズしてデータストアに保存
- ↑のシリアライズのためのクラスを作る
- ↑をprotoにしておけば、もし将来、別のマイクロサービスとかに切り出した場合もすぐに対応できるじゃん
っていう経緯です。
依存ライブラリにscalaPBのscalapb-json4sを追加する。 scalapb.github.io
libraryDependencies += "com.thesamet.scalapb" %% "scalapb-json4s" % "0.7.0"
サンプル
message ProtoJsonTest { string a = 1; int64 b = 2; repeated string c = 3; repeated ProtoJsonTestSub sub = 4; } message ProtoJsonTestSub { string x = 1; }
object Proto2JsonTest extends App { val proto = ProtoJsonTest( "hoge", 1L, Seq("aaa", "bbbb"), Seq(ProtoJsonTestSub("ham"), ProtoJsonTestSub("egg")) ) val r: String = JsonFormat.toJsonString(proto) println(r) // {"a":"hoge","b":"1","c":["aaa","bbbb"],"sub":[{"x":"ham"},{"x":"egg"}]} val desProto = JsonFormat.fromJsonString[ProtoJsonTest](r) println(proto == desProto) // true }