Scala将Map[String,Long]转换为JSON或JSON字符串



我有一个this对象:

case class UserStateSummaryByHourPayload (
ownerid: String,
userid: String,
team: String,
profile: String,
day: String,
hour: Int,
sortdate: String,
month: String,
durationpayload: Map[String, Long],
maxdurationpayload: Map[String, Long]
)

我想把两个Map属性转换成JSON或字符串(写入mysql列(,比如这个

case class JunkTest (
ownerid: String,
userid: String,
team: String,
profile: String,
day: String,
hour: Int,
sortdate: String,
month: String,
durationpayload: String,
maxdurationpayload: String
)

我试着按照其他人的指南做这样的事情,但没有奏效:

import com.fasterxml.jackson.module.scala.DefaultScalaModule;
import com.fasterxml.jackson.databind.ObjectMapper;
@transient val mapper = new ObjectMapper();
mapper.registerModule(DefaultScalaModule);
var junktest = ussapayloads.map(a => new JunkTest(
a.ownerid, 
a.userid,
a.team, 
a.profile, 
a.day, 
a.hour, 
a.sortdate, 
a.month, 
mapper.writeValueAsString(a.durationpayload),
mapper.writeValueAsString(a.maxdurationpayload)
));

如何获取Map[String,Long]并将其转换为JSON或JSON字符串?

Map("Online" -> 100,"Ready" -> 200)
{ "Online": 100, "Ready": 200 }

开始吧!

import spray.json._
import DefaultJsonProtocol._
object Demo1 extends App {
val keyValue = Map("Online" -> 100, "Ready" -> 200)

println(keyValue.toJson) //output {"Online":100,"Ready":200}
}

使用play-json非常简单:

import play.api.libs.json.Json
Json.stringify(Json.toJsObject(Map("Online" -> 100, "Ready" -> 200)))

代码运行可以在Scastie找到;

顺便说一句,你附加的代码工作得很好。你可以在Scastie找到它。

为了安装play-json,请将以下内容添加到您的build.sbt:

resolvers += "play-json" at "https://mvnrepository.com/artifact/com.typesafe.play/play-json"
libraryDependencies += "com.typesafe.play" %% "play-json" % "2.9.1"

相关内容

  • 没有找到相关文章

最新更新