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

encode #45

Open
swuecho opened this issue Feb 6, 2024 · 1 comment
Open

encode #45

swuecho opened this issue Feb 6, 2024 · 1 comment

Comments

@swuecho
Copy link
Owner

swuecho commented Feb 6, 2024

You can create a custom encoder for handling java.util.Date instances in Circe by utilizing the Encoder type class from the Circe library. Here's an example:

import io.circe._
import java.text.SimpleDateFormat
import java.util.Date

object DateEncoders {
  implicit val encodeDate: Encoder[Date] = new Encoder[Date] {
    val sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")

    override def apply(a: Date): Json = Json.fromString(sdf.format(a))
  }
}

In this example, we create a custom encoder for java.util.Date instances by implicitly defining an Encoder[Date]. Inside the Encoder instance, we define a SimpleDateFormat to format the date and then use it to convert the Date instance to a String representation, which is then wrapped in a Json object using Json.fromString.

To use this custom encoder, you can import it alongside the rest of your Circe code and Circe will use it automatically when encountering Date instances during encoding.

@swuecho
Copy link
Owner Author

swuecho commented Feb 6, 2024

In Scala 3, you can create a custom given instance for encoding java.time.LocalDateTime instances using Circe. Here's an example:

import io.circe._
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

object LocalDateTimeEncoders {
  given Encoder[LocalDateTime] with {
    val formatter: DateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME

    override def apply(a: LocalDateTime): Json = Json.fromString(formatter.format(a))
  }
}

In this example, we define a given instance of Encoder for java.time.LocalDateTime. Inside the given block, we define a DateTimeFormatter to format the LocalDateTime and then use it to convert the LocalDateTime instance to a String representation, which is then wrapped in a Json object using Json.fromString.

To use this custom encoder, you can import it alongside the rest of your Circe code and Circe will use it automatically when encountering LocalDateTime instances during encoding.

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

No branches or pull requests

1 participant