我有一个带有json的字符串,其属性包含破折号。我想将其转换为带下划线的对象。我尝试使用Json4s库,但出现了异常。
Exception in thread "main" org.json4s.package$MappingException: No usable value for some_field
Did not find value which can be converted into java.lang.String
您能帮我为带有破折号的字段写一些自定义策略吗?
转换代码:
import org.json4s.native.JsonMethods.parse
object Converter extends App {
case class Key(some_field: String, some_other_field: String)
def jsonToObject[A](data: String)(implicit manifest: Manifest[A]): A = {
import org.json4s.DefaultFormats
implicit val formats = DefaultFormats
parse(data).extract[A]
}
val input = "{\"some-field\":\"first\",\"some-other-field\":\"second\"}"
val someObject = jsonToObject[Key](input)
println(s"${someObject.some_field} ${someObject.some_other_field}")
}
答案 0 :(得分:0)
如果您不限于使用json4s,则可以使用jsoniter-scala轻松做到这一点:
libraryDependencies ++= Seq(
"com.github.plokhotnyuk.jsoniter-scala" %% "jsoniter-scala-core" % "2.6.2",
"com.github.plokhotnyuk.jsoniter-scala" %% "jsoniter-scala-macros" % "2.6.2" % "compile-internal" // or "provided", but it is required only in compile-time
)
import com.github.plokhotnyuk.jsoniter_scala.macros._
import com.github.plokhotnyuk.jsoniter_scala.core._
object Converter extends App {
case class Key(some_field: String, some_other_field: String)
implicit val codec: JsonValueCodec[Key] =
JsonCodecMaker.make(CodecMakerConfig.withFieldNameMapper(JsonCodecMaker.`enforce-kebab-case`))
val input = "{\"some-field\":\"first\",\"some-other-field\":\"second\"}"
val someObject = readFromString(input)
println(s"${someObject.some_field} ${someObject.some_other_field}")
}