Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

List serialization doesn't work with protobuf #93

Closed
Aschraf opened this issue Mar 6, 2018 · 3 comments
Closed

List serialization doesn't work with protobuf #93

Aschraf opened this issue Mar 6, 2018 · 3 comments
Assignees

Comments

@Aschraf
Copy link

Aschraf commented Mar 6, 2018

Serializing a list of objects succeeds in JSON and fails with Protobuf

fun main(args: Array<String>) {
  val list = listOf(Foo("a"), Foo("b"))

  println(JSON.stringify(Foo.serializer().list, list))
  println(ProtoBuf.dump(Foo.serializer().list, list))
}

@Serializable
data class Foo(@SerialId(1) val foo: String)

With the following error:

Exception in thread "main" java.util.NoSuchElementException: List is empty.
	at kotlin.collections.CollectionsKt___CollectionsKt.last(_Collections.kt:341)
	at kotlinx.serialization.TaggedOutput.getCurrentTag(Tagged.kt:163)
	at kotlinx.serialization.protobuf.ProtoBuf$ProtobufWriter.writeBegin(ProtoBuf.kt:47)
	at kotlinx.serialization.KOutput.writeBegin(Serialization.kt:163)
	at kotlinx.serialization.internal.ListLikeSerializer.save(CollectionSerializers.kt:45)
	at kotlinx.serialization.KOutput.write(Serialization.kt:99)
	at kotlinx.serialization.protobuf.ProtoBuf.dump(ProtoBuf.kt:415)
	at kotlinx.serialization.protobuf.ProtoBuf$Companion.dump(ProtoBuf.kt:403)
	at MainClassKt.main(MainClass.kt:21)
@sandwwraith
Copy link
Member

As far as I know, protobuf doesn't have a concept of "root-level list". There are no lists at all, just repeated objects with the same Tag. In your case, tag for Foo is not specified (and can't be). The easiest workaround for that is just wrap your list in some object and specify SerialId for it.

@JakeWharton
Copy link
Contributor

Root-level lists usually refer to delimited messages which are tagless, length-prefixed messages. They're almost always used for streaming, though, and not with buffered data.

@Aschraf
Copy link
Author

Aschraf commented Mar 6, 2018

That's exactly what I'm doing for now (wrapping the list in an object).
I misunderstood the documentation and thought the Protobuf serialization would do that for me.
The exception was a little bit misleading as It gave me the impression of an issue with my list.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants