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

Add example for decoding list of nodes #137

Closed
Deliganli opened this issue Sep 25, 2023 · 1 comment · Fixed by #138
Closed

Add example for decoding list of nodes #137

Deliganli opened this issue Sep 25, 2023 · 1 comment · Fixed by #138
Labels
enhancement New feature or request
Milestone

Comments

@Deliganli
Copy link

There are usually list of same named nodes in the XMLs I often interact with. Such as below

<foo>
  <bar>
    <baz>1</baz>
  </bar>
  <bar>
    <baz>2</baz>
  </bar>
  <bar>
    <baz>3</baz>
    <qux>A</qux>
  </bar>
</foo>

Couldn't figure out how to parse those list of bar s when writing decoders from cursors.

case class Baz(v: String)

implicit val bazD: Decoder[Baz] =
  Decoder.fromCursor(_.text.as[String]).map(Baz)

case class Qux(v: String)

implicit val quxD: Decoder[Qux] =
  Decoder.fromCursor(_.text.as[String]).map(Qux)

case class Bar(baz: Baz, qux: Option[Qux])

implicit val barD: Decoder[Bar] =
  Decoder.fromCursor { c =>
    (
      c.down("baz").as[Baz],
      c.down("qux").as[Option[Qux]]
    ).mapN(Bar.apply)
  }

case class Foo(bar: List[Bar])

implicit val fooD: Decoder[Foo] =
  Decoder.fromCursor { c =>
    c.down("bar")
      .as[???] // How to decode the list of nodes here?
      .map(Foo.apply)
  }

.as[List[Bar]] doesn't work because List decoders are expecting comma separated strings as I understand.

Maybe we can add an example to decoders to how to decode such nodes.

@geirolz
Copy link
Owner

geirolz commented Sep 27, 2023

Nice spot. This is actually a problem.
I've just opened a PR to fix this providing a prover Decoder[List[T]] implementation.

Let me know what do you think about it

#138

Once merged you can use

implicit val fooD: Decoder[Foo] =
  Decoder.fromCursor { c =>
    c.down("bar")
      .as[List[Bar]]
      .map(Foo.apply)
  }

@geirolz geirolz added the enhancement New feature or request label Sep 27, 2023
@geirolz geirolz added this to the v0.0.12 milestone Sep 27, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants