Nima
Nima

Reputation: 190

Upickle: read an attribute that may be a String or Int as a String

I have a field that may come from a rest api as a String or Int, but when I read it I always want to read it as a String, i.e. if it comes as an Int I want to do a toString on it

    case class ZoneList(
        someField: Int,
        targetField: String
    )

    object ZoneList {
      implicit val rw: ReadWriter[ZoneList] = macroRW
    }

targetField is the field in question Looking at http://www.lihaoyi.com/upickle/#CustomPicklers, but still dont think I have enough of a handle to start a custom pickler

edit:

ended up doing this

implicit val anyToStringReader: Reader[Option[String]] =
    reader[ujson.Value].map[Option[String]] { j =>
      Try(j.toString()).toOption
    }

Would have preferred if I could single out the targetField attribute only but my actual case class has a lot of fields and don't think I can do that and also utilize the default macro. If anyone knows how let me know

Upvotes: 0

Views: 256

Answers (1)

Nima
Nima

Reputation: 190

Solved by lihaoyi in the upickle gitter:

"if you want to single out that attribute, give it a new type that’s a wrapper around Option String and write your pickler for that type"

Upvotes: 0

Related Questions