duckertito duckertito - 1 year ago 241
Scala Question


I use

to parse JSON strings to

def parseJSON(line: String): Map[String, String] = {
JacksMapper.readValue[Map[String, String]](line)

For some JSON strings it throws the error:

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_ARRAY token

In particular it happens with this string:


I assume that the problem is with
, while I expect the result as
. So, in this case I would be interested to convert arrays to strings like
. How can I do it flexibly so that the solution would be adaptable to other possible fields that might be arrays in some cases?

In my case I never have complex arrays that should be parsed with a static class. Only arrays of numbers or strings.

Answer Source

You could do it in two steps:

  1. Parse JSON without caring of the value type
  2. Map the values and transform them if needed

That could give something like:

def parseJSON(line: String): Map[String, String] = {
  JacksMapper.readValue[Map[String, Any]](line)
    .mapValues {
      case array: Iterable[Any] => array.mkString(", ")
      case anyValue: Any        => anyValue.toString
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download