简体   繁体   中英

Why toString does not work when String.valueOf() works at casting

I need to parse Json into Map[String,String] structure. Json may contain numeric and string types as values.

So in order to store it as String I've applied toString method and it throws ClassCastException. However if String.valueOf() is applied everything is OK.

  1. Why so?
  2. If there are better way to do such casting?
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule

import scala.collection.Map
import scala.util.parsing.json.JSON

val mapper = new ObjectMapper()
mapper.registerModule(DefaultScalaModule)


val str = "[ { \"name\": \"VehicleType\", \"value\": 11 }, { \"name\": \"VehicleWeight\", \"value\": \"12000\" } ]"
val customfields = JSON.parseFull(str) match {
  case Some(map: List[Map[String, String]]) =>
    // map.map(map => {map("name") -> map("value").toString}).toMap

    // that throws:
    // java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.String
    //  at #worksheet#.$anonfun$customfields$1.apply(scratch.scala2:14)
    //  at #worksheet#.$anonfun$customfields$1.apply(scratch.scala2:14)
    //  at scala.collection.immutable.List.map(scratch.scala2:269)
    //  at #worksheet#.customfields$lzycompute(scratch.scala2:14)

    // that works fine 
    map.map(map => {map("name") -> String.valueOf(map("value"))}).toMap
  case _ => Map.empty[String, String]
}

Because the pattern matching match the List type, but doesn't go all the way to all types inside the map, that's why you enter the Some clause.

So, instead of the case Some(map: List[Map[String, String]]) =>

Try do this:

case Some(map: List[Map[String, _]]) =>
     map.map(map => {map("name") -> 
     map("value") match {
     case s: String => s
     case i: java.lang.Number => i
     case unexpectedType => throw Exception(s"Unexpected type $unexpectedType")
   }.toString}).toMap

That's how you can handle every value in your map safely.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM