【问题标题】:How to parse json using json4s so that let primitive values become custom case class?如何使用 json4s 解析 json 以便让原始值成为自定义案例类?
【发布时间】:2019-11-17 09:21:29
【问题描述】:

我想用case类来替换json4s中的原始类型,因为我想把业务方法放在这些case类中。

例如:

import org.json4s.{CustomSerializer, DefaultFormats, NoTypeHints}
import org.json4s.JsonAST.{JField, JInt, JObject}
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization.read

object Json4sExercise {

  trait ObjectHolder[T] {
  }

  case class IntValue(v: Int) extends ObjectHolder[Int]

  case class StringValue(v: String) extends ObjectHolder[String]

  class IntSerializer extends CustomSerializer[IntValue](format => ( {
    case JInt(x) => IntValue(x.toInt)
  }, {
    case IntValue(x) => JInt(BigInt(x))
  }
  ))

  implicit val formats =  Serialization.formats(NoTypeHints) + new IntSerializer

  def main(args: Array[String]): Unit = {
    println(read[Map[String, _]](""" {"price":350} """))
  }

}

但不是我想要的:Map(price -> IntValue(x:350)),而是打印 Map(price -> 350)

【问题讨论】:

标签: scala json4s


【解决方案1】:

您需要具体说明您要阅读的类型

println(read[Map[String, IntValue]](""" {"price":350} """))
Map(price -> IntValue(350))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-27
    • 2015-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多