Skip to content

Wire JSON

Wire offers JSON serialization over Moshi or Gson. We provide an adapter factory for both to configure them to deal with protobuf specifics.

Moshi

Moshi support is part of the wire-moshi-adapter module. It has to be added to the project dependencies in order to plug the WireJsonAdapterFactory into Moshi.

The Maven coordinates are: com.squareup.wire:wire-moshi-adapter:<version>

val moshi = Moshi.Builder()
      .add(WireJsonAdapterFactory())
      .build()

val adapter = moshi.adapter(Pizza::class.java)
val pizza: Pizza = ...
val json = adapter.toJson(pizza)
val parsedPizza = adapter.fromJson(json)

Gson

Moshi support is part of the wire-gson-support module. It has to be added to the project dependencies in order to plug the WireTypeAdapterFactory into Gson.

The Maven coordinates are: com.squareup.wire:wire-gson-support:<version>

val gson = GsonBuilder()
      .registerTypeAdapterFactory(WireTypeAdapterFactory())
      .create()

val adapter = gson.adapter(Pizza::class.java)
val pizza: Pizza = ...
val json = adapter.toJson(pizza)
val parsedPizza = adapter.fromJson(json)

R8 and ProGuard

The wire-runtime jar contains R8 and ProGuard rules for the types and members that the runtime finds by name. R8 and ProGuard read these rules from the jar, so you do not have to copy them.

The JSON adapters use reflection to read the fields, builders and nested classes of each message. Java code that Wire generates with compact = true uses the same reflection for all encoding and decoding, not only for JSON. Wire cannot know which messages your app converts to JSON, or which messages are compact, so your app must keep them. Keep each of these messages, its builder and other nested classes, and the messages and enums that its fields use:

-keep class com.example.Pizza { *; }
-keep class com.example.Pizza$* { *; }

Protoc

Wire is interoperable with protoc for all proto3 messages. The JSON representation of proto2 is unspecified. JSON representations of proto2 messages from Wire and protoc are not interoperable. Note that by default Protoc throws an error for unknown fields. Wire will ignore them.