amnaredo / test

0 stars 0 forks source link

Encode Longs as number #224

Open amnaredo opened 2 years ago

amnaredo commented 2 years ago

Is there a way to override the default conversion of Long types to String and convert them to integer?

E.g. instead of having this (note that propertyId is a Long and updatedTs is a unix timestamp == Long):

{
   "propertyId": "54",
    "updatedTs": "1523885841319"
}

have this:

{
   "propertyId": 54,
    "updatedTs": 1523885841319
}

I know this issue was raised in https://github.com/lihaoyi/upickle/issues/66 , but could you please provide some examples how to override the implementation ? A possible implementation of Reader/Writer? What do we need to do to use it (which packages to import, which objects/methods to implement,etc.)?

ID: 226 Original Author: ricardogaspar2

amnaredo commented 2 years ago

http://www.lihaoyi.com/upickle/#CustomPicklers Original Author: lihaoyi

amnaredo commented 2 years ago

For sure I'm not doing it right.... @lihaoyi can you help me overriding the Long Reader and Writer?

My sample code


import ujson.AbortJsonProcessingException

//import MyPickler.{macroRW, ReadWriter => RW}
object TestJsonLong {
  object MyPickler extends upickle.AttributeTagged {
    override implicit val LongWriter: Writer[Long] = new IntegralNumWriter(_.toDouble)
    override implicit val LongReader: Reader[Long] = new IntegralNumReader(_.toLong,
                                                                           l =>
                                                                             if (l > Long.MaxValue || l < Long.MinValue) throw new AbortJsonProcessingException("expected long") else l.toLong)
}

  def main(args: Array[String]): Unit = {

    // int example
    val anInt: Int = 123
    val jint:ujson.Js = ujson.write(anInt:Int)
    val defaultIntOutput:String = "\""+ anInt.toString + "\""
    println(s"jint.toString(): ${jint.toString}")
    println(s"defaultIntOutput: ${defaultIntOutput}")
    assert(jint.toString().equals(defaultIntOutput)) // WORKS - normal beaviour

    // long example
    val myLong = 12345L
    val jlong:ujson.Js = ujson.write(myLong:Long)
    val expectedOutput:String = "\"" + myLong.toString + "\""
    val defaultOutput:String = "\"\\\"" + myLong.toString + "\\\"\""

    println(s"json.toString(): ${jlong.toString}")
    println(s"defaultOutput: ${defaultOutput}")
    println(s"expectedOutput: ${expectedOutput}")

    assert(jlong.toString().equals(defaultOutput)) // WORKS - normal beaviour
    assert(jlong.toString() == expectedOutput) // DOESN'T WORK

  }
}

Original Author: ricardogaspar2