JSON and Scala Seq

I have a scala class like class A(b:Seq[String])

My problem is that I am deserializing it from text that has no field bin my class contains null. Is it possible to force the desrealizer to fill empty Seq?

I use com.fasterxml.jackson.databind.ObjectMapperwith com.fasterxml.jackson.module.scala.DefaultScalaModule.

EDIT: I want a solution that captures all such fields without explicitly mentioning their complete list. Ir changes all ads.

+4
source share
3 answers

Jackson is not currently supported.

You can see the corresponding GitHub ticket here: https://github.com/FasterXML/jackson-databind/issues/347

null Seq :

class A(_b: Seq[String]) {
  val b = _b match {
    case null => Nil
    case bs => bs
  }
}

( fooobar.com/questions/1517882/... )

+5

Spray JSON, , b, :

import spray.json._

case class A(b: Seq[String])

object Protocol extends DefaultJsonProtocol {
  implicit def aFormat = jsonFormat1(A)
}

import Protocol._

val str1 = """{ "b" : [] }""""
val str2 = """{ "b" : ["a", "b", "c"] }""""
val str3 = """{}"""
str1.parseJson.convertTo[A]//successful
str2.parseJson.convertTo[A]//successful
str3.parseJson.convertTo[A]//Deserialization error

Spray JSON , A:

import spray.json._

case class A(b: Seq[String])

object Protocol extends DefaultJsonProtocol {

  implicit object aFormat extends RootJsonFormat[A] {
    override def write(obj: A): JsValue = JsObject("b" -> obj.b.toJson)

    override def read(json: JsValue): A = json match {
      //Case where the object has exactly one member, 'b'
      case JsObject(map) if map.contains("b") && map.size == 1 => A(map("b").convertTo[Seq[String]])
      //Case where the object has no members
      case JsObject(map) if map.isEmpty => A(Seq())
      //Any other json value, which cannot be converted to an instance of A
      case _ => deserializationError("Malformed")
    }
  }
}

import Protocol._

val str1 = """{ "b" : [] }""""
val str2 = """{ "b" : ["a", "b", "c"] }""""
val str3 = """{}"""
str1.parseJson.convertTo[A]//successful
str2.parseJson.convertTo[A]//successful
str3.parseJson.convertTo[A]//successful
+1

String jackson, , , - ( ), jackson-module 2.1.2. Seq. https://github.com/FasterXML/jackson-module-scala/issues/48

0

Source: https://habr.com/ru/post/1609018/


All Articles