-
-
Notifications
You must be signed in to change notification settings - Fork 99
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
Handling same field with different value type #1214
Comments
@HelloJeevan Thanks for the question! If you just need to parse both numeric and stringified JSON values as implicit val customCodecOfInt: JsonValueCodec[Int] = new JsonValueCodec[Int] {
def decodeValue(in: JsonReader, default: Int): Int =
if (in.isNextToken('"')) {
in.rollbackToken()
in.readStringAsInt()
} else {
in.rollbackToken()
in.readInt()
}
def encodeValue(x: Int, out: JsonWriter): Unit = out.writeVal(x)
def nullValue: Int = 0
} Also, please, see more advanced example of JavaScript compatible codec for |
Hey @plokhotnyuk thanks for replying really appriciate that |
Here is a script that tests the proposed solution for you: //> using dep "com.github.plokhotnyuk.jsoniter-scala::jsoniter-scala-core::2.31.0"
//> using compileOnly.dep "com.github.plokhotnyuk.jsoniter-scala::jsoniter-scala-macros::2.31.0"
import com.github.plokhotnyuk.jsoniter_scala.macros._
import com.github.plokhotnyuk.jsoniter_scala.core._
case class Person(name: String, id: Int)
implicit val customCodecOfInt: JsonValueCodec[Int] = new JsonValueCodec {
def decodeValue(in: JsonReader, default: Int): Int =
if (in.isNextToken('"')) {
in.rollbackToken()
in.readStringAsInt()
} else {
in.rollbackToken()
in.readInt()
}
def encodeValue(x: Int, out: JsonWriter): Unit = out.writeVal(x)
def nullValue: Int = 0
}
implicit val personCodec: JsonValueCodec[Person] = JsonCodecMaker.make
val person = try readFromStream[Person](System.in) catch {
case ex: Throwable => ex.printStackTrace(System.err)
}
println(person) It accepts JSON string from scala-cli script.sc <<< '{"name": "foo", "id": "2604"}'
scala-cli script.sc <<< '{"name": "foo", "id": 2604}' Expected output for both inputs is the same: Person(foo,2604) |
Hey,
Actually i am using
jsoniter-scala
lib but i am having situation like thisCan we desrialize the json request in which we get same field sometime as integer and sometime as string with having same case class...i have tried using
Either
andAnyVal
data type but not able to implement itI am open to all method to handle this kind of situation
Thanks
The text was updated successfully, but these errors were encountered: