本文整理汇总了Scala中com.fasterxml.jackson.module.scala.DefaultScalaModule类的典型用法代码示例。如果您正苦于以下问题:Scala DefaultScalaModule类的具体用法?Scala DefaultScalaModule怎么用?Scala DefaultScalaModule使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DefaultScalaModule类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: CustomObjectMapperModule
//设置package包名称以及导入依赖的类
package modules
import javax.inject.{Inject, Provider, Singleton}
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import play.api.inject.{ApplicationLifecycle, Module}
import play.api.{Configuration, Environment}
import play.libs.Json
import scala.concurrent.Future
class CustomObjectMapperModule extends Module {
def bindings(environment: Environment, configuration: Configuration) = Seq(
bind[ObjectMapper].toProvider[ObjectMapperProvider].eagerly()
)
}
@Singleton
class ObjectMapperProvider @Inject() (lifecycle: ApplicationLifecycle) extends Provider[ObjectMapper] {
lazy val get : ObjectMapper = {
val objectMapper = Json.newDefaultMapper()
objectMapper.registerModule(DefaultScalaModule)
Json.setObjectMapper(objectMapper)
lifecycle.addStopHook { () =>
Future.successful(Json.setObjectMapper(null))
}
objectMapper
}
}
开发者ID:oen9,项目名称:bard-api,代码行数:34,代码来源:CustomObjectMapperModule.scala
示例2: JsonUtil
//设置package包名称以及导入依赖的类
import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper}
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
object JsonUtil {
val mapper = new ObjectMapper() with ScalaObjectMapper
mapper.registerModule(DefaultScalaModule)
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
def toJson(value: Map[Symbol, Any]): String = {
toJson(value map { case (k,v) => k.name -> v})
}
def toJson(value: Any): String = {
mapper.writeValueAsString(value)
}
def toMap[V](json:String)(implicit m: Manifest[V]) = fromJson[Map[String,V]](json)
def fromJson[T](json: String)(implicit m : Manifest[T]): T = {
mapper.readValue[T](json)
}
}
object MarshallableImplicits {
implicit class Unmarshallable(unMarshallMe: String) {
def toMap: Map[String,Any] = JsonUtil.toMap(unMarshallMe)
//def toMapOf[V]()(implicit m: Manifest[V]): Map[String,V] = JsonUtil.toMapOf[V](unMarshallMe)
def fromJson[T]()(implicit m: Manifest[T]): T = JsonUtil.fromJson[T](unMarshallMe)
}
implicit class Marshallable[T](marshallMe: T) {
def toJson: String = JsonUtil.toJson(marshallMe)
}
}
开发者ID:hoover,项目名称:language,代码行数:39,代码来源:JsonUtil.scala
示例3: BaseBDBEntity
//设置package包名称以及导入依赖的类
package db
import java.util.{Date, UUID}
import com.fasterxml.jackson.databind.{SerializationFeature, ObjectMapper}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import tools._
import common._
import Tool._
class BaseBDBEntity[+Self <: BaseBDBEntity[Self]](tableName: String) extends BDBEntity(tableName) {
def toJson: String = {
BaseBDBEntity.map.writeValueAsString(this)
}
def fromJson(json: String): Self = {
BaseBDBEntity.map.readValue(json, this.getClass).asInstanceOf[Self]
}
//????????????
def changeUpdateBean(): Self = {
fromJson(toJson)
}
override def queryById(id: String, fields: String*): Option[Self] = {
super.queryById(id,fields:_*) map (_.asInstanceOf[Self])
}
override def queryByIds(idName: String, ids: List[Long], fields: String*): List[Self] = {
super.queryByIds(idName,ids,fields:_*) map (_.asInstanceOf[Self])
}
//????????????
override def queryPage(where: String, pageNum: Int, pageSize: Int, fields: String*):List[Self] = {
val list = super.queryPage(where, pageNum, pageSize,fields: _*)
list map (_.asInstanceOf[Self])
}
}
object BaseBDBEntity {
private val map = new ObjectMapper() with ScalaObjectMapper
map.registerModule(DefaultScalaModule)
map.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
}
//??????
class LoanData(val id:String=UUID.randomUUID().toString,val Title:String="",val text:String="",val createTime:Date=new Date())extends BaseBDBEntity[LoanData]("LoanData")
开发者ID:livehl,项目名称:paipai,代码行数:49,代码来源:BDBClass.scala
示例4: JsonObjectMapper
//设置package包名称以及导入依赖的类
package de.stema.util
import javax.inject.Singleton
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper, SerializationFeature}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import de.stema.pullrequests.dto.PullRequestDTO
import scala.reflect.ClassTag
import scala.util.{Failure, Success, Try}
@Singleton
class JsonObjectMapper {
private lazy val mapper = new ObjectMapper with ScalaObjectMapper
mapper.registerModule(DefaultScalaModule)
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
mapper.configure(SerializationFeature.INDENT_OUTPUT, true)
mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
def getInstance[T](json: String)(implicit ct: ClassTag[T]): T =
Try {
mapper.readValue(json, ct.runtimeClass).asInstanceOf[T]
} match {
case Success(instance) => instance
case Failure(e) => throw new IllegalStateException(s"Error during parsing of '$json'", e)
}
def getInstances[T](json: String)(implicit ct: ClassTag[T]): Seq[PullRequestDTO] =
Try {
mapper.readValue[Seq[PullRequestDTO]](json)
} match {
case Success(instances) => instances
case Failure(e) => throw new IllegalStateException(s"Error during parsing of '$json'", e)
}
}
开发者ID:callidustaurus,项目名称:github-api,代码行数:39,代码来源:JsonObjectMapper.scala
示例5: ProvisionUser
//设置package包名称以及导入依赖的类
// Copyright (c) 2017 Grier Forensics. All Rights Reserved.
package com.grierforensics.greatdane.connector
import java.net.URI
import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Paths}
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import org.apache.commons.io.IOUtils
import org.apache.http.HttpHeaders
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.HttpClients
object ProvisionUser {
def main(args: Array[String]): Unit = {
def die = {
println("Usage: provision-user <email-address> [<certificate file>]")
sys.exit(1)
}
val (emailAddress, certPem) = args.toList match {
case email :: tail => tail match {
case Nil => (email, "")
case certFile :: Nil => (email, new String(Files.readAllBytes(Paths.get(certFile)), StandardCharsets.UTF_8))
case _ => die
}
case _ => die
}
val client = HttpClients.createDefault()
val uri = new URI(s"http://${Settings.Host}:${Settings.Port}/api/v1/user/$emailAddress")
val post = new HttpPost(uri)
post.addHeader(HttpHeaders.CONTENT_TYPE, "application/json")
post.addHeader(HttpHeaders.AUTHORIZATION, Settings.ApiKey)
println(post.toString)
val req = ProvisionRequest(None, if (certPem.length > 0) Some(Seq(certPem)) else None)
val mapper = new ObjectMapper().registerModule(DefaultScalaModule)
val json = mapper.writeValueAsString(req)
println(json)
post.setEntity(new StringEntity(json))
val resp = client.execute(post)
try {
val entity = resp.getEntity
println(resp.getStatusLine.getStatusCode, resp.getStatusLine.getReasonPhrase)
println(IOUtils.toString(entity.getContent, StandardCharsets.UTF_8))
} finally {
resp.close()
}
}
}
开发者ID:grierforensics,项目名称:Great-DANE-Connector,代码行数:59,代码来源:ProvisionUser.scala
示例6: JsonUtil
//设置package包名称以及导入依赖的类
package util
import java.io.StringWriter
import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import scala.reflect.{ClassTag, Manifest}
object JsonUtil {
val mapper = new ObjectMapper() with ScalaObjectMapper
mapper.registerModule(DefaultScalaModule)
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
def toJson[T](data: T): String = {
val out = new StringWriter()
mapper.writeValue(out, data)
out.toString
}
def fromJson[T: ClassTag](json: String)(implicit m: Manifest[T]): T =
mapper.readValue[T](json)
}
开发者ID:SarathChandran,项目名称:InventoryTracker,代码行数:26,代码来源:JsonUtil.scala
示例7: Truck
//设置package包名称以及导入依赖的类
package controllers
import scala.collection.JavaConverters._
import com.fasterxml.jackson.databind.{ ObjectMapper, JsonNode }
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import play.api.Play
import sys.process._
case class Truck (
name: String,
address: String,
cuisine: List[String],
url: String) {
override def toString: String = s"""$name (${cuisine.mkString(",")}) @ $address [$url]"""
}
object Truck {
def newObjectMapper: ObjectMapper = {
val m = new ObjectMapper()
m.registerModule(DefaultScalaModule)
}
private[Truck] lazy val mapper = newObjectMapper
val defaultLat = Play.maybeApplication.flatMap(_.configuration.getDouble("foodtrucks.latitude")).getOrElse(0.0)
val defaultLon = Play.maybeApplication.flatMap(_.configuration.getDouble("foodtrucks.longitude")).getOrElse(0.0)
def apply(jsonNode: JsonNode): Truck = {
val info = jsonNode.get("obj")
Truck(
info.get("name").asText,
info.get("last_seen").get("address").asText,
info.get("cuisine").elements.asScala.map(_.asText).toList,
info.get("url").asText
)
}
def listAll(lat: Double = defaultLat, lon: Double = defaultLon): List[Truck] = {
val result = Seq("curl", "-XGET", s"http://nyctruckfood.com/api/trucks/search?q=$lat,$lon").!!
mapper.readTree(result).elements.asScala.map(Truck(_)).toList
}
}
开发者ID:andy327,项目名称:slack-foodtrucks,代码行数:44,代码来源:Truck.scala
示例8: JsonMarshaller
//设置package包名称以及导入依赖的类
package services.json
import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
object JsonMarshaller {
val mapper = new ObjectMapper with ScalaObjectMapper
mapper.registerModule(DefaultScalaModule)
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
def toJson(value: Any): String = {
mapper.writeValueAsString(value)
}
def toMap[V](json:String)(implicit m: Manifest[V]) = fromJson[Map[String,V]](json)
def fromJson[T](json: String)(implicit m : Manifest[T]): T = {
mapper.readValue[T](json)
}
}
object MarshallableImplicits {
implicit class Unmarshallable(unMarshallMe: String) {
def toMapOf[V]()(implicit m: Manifest[V]): Map[String,V] = JsonMarshaller.toMap[V](unMarshallMe)
def fromJson[T]()(implicit m: Manifest[T]): T = JsonMarshaller.fromJson[T](unMarshallMe)
}
implicit class Marshallable[T](marshallMe: T) {
def toJson: String = JsonMarshaller.toJson(marshallMe)
}
}
开发者ID:jeroenr,项目名称:reactive-mongo-demo,代码行数:34,代码来源:JsonMarshaller.scala
示例9: BankAccountEventHandler
//设置package包名称以及导入依赖的类
package org.styx.mongo
import java.util.concurrent.Executors
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import org.styx.bank.example.events._
import org.styx.bank.example.state.BankAccount
import org.styx.handler.{EventFetcher, EventHandler}
import org.styx.model.Event
import scala.concurrent.ExecutionContext
object BankAccountEventHandler {
implicit val ec = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(30))
val mapper = new ObjectMapper
mapper.registerModule(DefaultScalaModule)
def converter: MongoDBEvent => Event[BankAccount] = { mongoDBEvent =>
val event = mongoDBEvent match {
case MongoDBEvent("BankAccountCreated", eventDate, version, _, _) => BankAccountCreated(version, eventDate)
case MongoDBEvent("BankAccountClosed", eventDate, version, _, _) => BankAccountClosed(version, eventDate)
case MongoDBEvent("OwnerChanged", eventDate, version, _, _) => OwnerChanged(version, eventDate)
case MongoDBEvent("DepositPerformed", eventDate, version, _, _) => DepositPerformed(version, eventDate)
case MongoDBEvent("WithdrawalPerformed", eventDate, version, _, _) => WithdrawalPerformed(version, eventDate)
}
event.data = mapper.readValue(mongoDBEvent.data.toJson(), classOf[Map[String, Any]])
event
}
implicit val eventHandler: EventHandler[BankAccount] with EventFetcher[BankAccount] = MongoDBEventHandlerFetcher(MongoD.collection, mapper, converter)
}
开发者ID:gabfssilva,项目名称:styx,代码行数:36,代码来源:BankAccountEventHandler.scala
示例10: TopicUtils
//设置package包名称以及导入依赖的类
package com.groupon.dse.kafka.topic
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
object TopicUtils {
def extractTopicListFromJson(json: String): List[TopicAndMetadata] = {
val mapper = new ObjectMapper()
mapper.registerModule(DefaultScalaModule)
//The top level "topics" key is mapped to a list of [[TopicAndMetadata]] objects
val contentMap = mapper.readValue(json, classOf[Map[String, List[Map[String, AnyRef]]]])
val topics = contentMap.getOrElse("topics", List.empty)
val topicList = topics.map(topicMap => {
val topic = topicMap.getOrElse("name", "")
val metadata = topicMap.getOrElse("metadata", Map.empty)
TopicAndMetadata(topic.toString, metadata.asInstanceOf[Map[String, AnyRef]])
}).filterNot(_.name.isEmpty)
topicList
}
}
开发者ID:groupon,项目名称:baryon,代码行数:25,代码来源:TopicUtils.scala
示例11: WebsocketFeed
//设置package包名称以及导入依赖的类
package moe.pizza.zkapi
import java.net.URI
import com.fasterxml.jackson.databind.{DeserializationConfig, ObjectMapper}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import moe.pizza.zkapi.zkillboard.Killmail
import org.eclipse.jetty.websocket.api.{WebSocketListener, Session, WebSocketAdapter}
import org.eclipse.jetty.websocket.client.WebSocketClient
import org.slf4j.{LoggerFactory, Logger}
import scala.concurrent.duration._
object WebsocketFeed {
def main (args: Array[String]) {
val logger = LoggerFactory.getLogger("main")
val ws = createClient("ws://ws.eve-kill.net/kills", {s: Killmail => logger.info(s.toString)})
ws.start()
Thread.sleep(10.seconds.toMillis)
}
def createClient(url: String, onrecv: (Killmail => Unit)): WebSocketClient = {
val OM = new ObjectMapper()
OM.registerModule(DefaultScalaModule)
val logger = LoggerFactory.getLogger("websockets")
class EKWSClientSocket(callback: (Killmail => Unit)) extends WebSocketAdapter {
override def onWebSocketText(message: String): Unit = {
if (message.startsWith("{")) {
val kill = OM.readValue(message, classOf[zkillboard.Killmail])
callback(kill)
}
}
}
val ws = new WebSocketClient()
ws.start()
ws.connect(new EKWSClientSocket(onrecv), URI.create(url))
ws
}
}
开发者ID:greg2010,项目名称:pizza-eveapi-mirror,代码行数:49,代码来源:WebsocketFeed.scala
示例12: RedisQSpec
//设置package包名称以及导入依赖的类
package moe.pizza.zkapi
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import moe.pizza.zkapi.StatsTypes.SuperPilot
import org.scalatest.{FlatSpec, MustMatchers}
import scala.io.Source
class RedisQSpec extends FlatSpec with MustMatchers {
"redisq responses" should "be parsed" in {
val json = Source.fromInputStream(getClass.getResourceAsStream("/redisq.json")).getLines().mkString("\n")
val OM = new ObjectMapper()
OM.registerModule(DefaultScalaModule)
val r = OM.readValue[RedisQTypes.RedisQResponse](json, classOf[RedisQTypes.RedisQResponse])
r.payload.isDefined must equal(true)
r.payload.get.killID must equal(51738685)
}
"redisq responses 2" should "be parsed" in {
val json = Source.fromInputStream(getClass.getResourceAsStream("/redisq2.json")).getLines().mkString("\n")
val OM = new ObjectMapper()
OM.registerModule(DefaultScalaModule)
val r = OM.readValue[RedisQTypes.RedisQResponse](json, classOf[RedisQTypes.RedisQResponse])
r.payload.isDefined must equal(true)
r.payload.get.killID must equal(51738559)
}
"redisq responses 3" should "be parsed" in {
val json = Source.fromInputStream(getClass.getResourceAsStream("/redisq3.json")).getLines().mkString("\n")
val OM = new ObjectMapper()
OM.registerModule(DefaultScalaModule)
val r = OM.readValue[RedisQTypes.RedisQResponse](json, classOf[RedisQTypes.RedisQResponse])
r.payload.isDefined must equal(false)
}
"redisq responses 4, attacker with faction" should "be parsed" in {
val json = Source.fromInputStream(getClass.getResourceAsStream("/redisq4_attackerwithfaction.json")).getLines().mkString("\n")
val OM = new ObjectMapper()
OM.registerModule(DefaultScalaModule)
val r = OM.readValue[RedisQTypes.RedisQResponse](json, classOf[RedisQTypes.RedisQResponse])
r.payload.isDefined must equal(true)
val factionedattacker = r.payload.get.killmail.attackers.find(_.faction.isDefined)
factionedattacker.get.faction.get.name must equal("Blood Raider Covenant")
}
"redisq responses 5, victim with faction" should "be parsed" in {
val json = Source.fromInputStream(getClass.getResourceAsStream("/redisq5_victimwithfaction.json")).getLines().mkString("\n")
val OM = new ObjectMapper()
OM.registerModule(DefaultScalaModule)
val r = OM.readValue[RedisQTypes.RedisQResponse](json, classOf[RedisQTypes.RedisQResponse])
r.payload.isDefined must equal(true)
r.payload.get.killmail.victim.faction.get.name must equal("Gallente Federation")
}
}
开发者ID:greg2010,项目名称:pizza-eveapi-mirror,代码行数:60,代码来源:RedisQSpec.scala
示例13: StatsSpec
//设置package包名称以及导入依赖的类
package moe.pizza.zkapi
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import moe.pizza.zkapi.StatsTypes.SuperPilot
import org.scalatest.{MustMatchers, FlatSpec}
import scala.io.Source
class StatsSpec extends FlatSpec with MustMatchers {
"alliance stats" should "be parsed" in {
val json = Source.fromInputStream(getClass.getResourceAsStream("/alliancestats.json")).getLines().mkString("\n")
val OM = new ObjectMapper()
OM.registerModule(DefaultScalaModule)
val r = OM.readValue[StatsTypes.AllianceInfo](json, classOf[StatsTypes.AllianceInfo])
val superpilots = r.supers.supercarriers.data ++ r.supers.titans.data
superpilots.size must equal(199)
superpilots.head must equal(new SuperPilot(105,93260759,"Doctor Chalke"))
}
"alliance stats 2" should "be parsed" in {
val json = Source.fromInputStream(getClass.getResourceAsStream("/alliancestats2.json")).getLines().mkString("\n")
val OM = new ObjectMapper()
OM.registerModule(DefaultScalaModule)
val r = OM.readValue[StatsTypes.AllianceInfo](json, classOf[StatsTypes.AllianceInfo])
val superpilots = r.getSupers ++ r.getTitans
superpilots.isEmpty must equal(true)
}
"alliance stats 3" should "be parsed" in {
val json = Source.fromInputStream(getClass.getResourceAsStream("/alliancestats3.json")).getLines().mkString("\n")
val OM = new ObjectMapper()
OM.registerModule(DefaultScalaModule)
val r = OM.readValue[StatsTypes.AllianceInfo](json, classOf[StatsTypes.AllianceInfo])
val superpilots = r.getSupers ++ r.getTitans
println(superpilots)
}
}
开发者ID:greg2010,项目名称:pizza-eveapi-mirror,代码行数:42,代码来源:StatsSpec.scala
示例14: JacksonMapper
//设置package包名称以及导入依赖的类
package config
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper}
import com.fasterxml.jackson.dataformat.javaprop.JavaPropsMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
object JacksonMapper extends ObjectMapper {
configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true)
registerModule(DefaultScalaModule)
setSerializationInclusion(JsonInclude.Include.NON_ABSENT)
}
// Instead of converting to/from JSON, this converts to/from nested key/value properties.
object JacksonPropertyMapper extends JavaPropsMapper {
configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true)
registerModule(DefaultScalaModule)
setSerializationInclusion(JsonInclude.Include.NON_ABSENT)
def productToKeyVals(p: Product): List[(String, String)] = {
// This is a naive two-stage algorithm that works simply. Maybe it could be improved later.
val props = writeValueAsString(p)
val lines = props.split('\n')
val keyVals =
for (line <- lines
if line.length > 1) yield {
divide(line, '=')
}
keyVals.toList
}
private def divide(s: String, c: Char): (String, String) = {
val i = s.indexOf(c)
if (i < 0) s -> ""
else {
val w1 = s.substring(0, i)
val rest = s.substring(i + 1)
w1 -> rest
}
}
}
开发者ID:hmrc,项目名称:bank-account-reputation-frontend,代码行数:44,代码来源:JacksonMapper.scala
示例15: GenericJsonSupport
//设置package包名称以及导入依赖的类
package com.flipkart.connekt.receptors.wire
import akka.http.scaladsl.marshalling.{PredefinedToEntityMarshallers, ToEntityMarshaller}
import akka.http.scaladsl.model.MediaTypes
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, PredefinedFromEntityUnmarshallers}
import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import com.flipkart.connekt.receptors.wire.GenericJsonSupport._
import scala.collection.mutable
import scala.reflect.ClassTag
object GenericJsonSupport {
val jacksonModules = Seq(DefaultScalaModule)
val mapper = new ObjectMapper() with ScalaObjectMapper
mapper.registerModules(jacksonModules: _*)
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
val m: mutable.Map[Class[_], ToEntityMarshaller[_]] = mutable.Map.empty[Class[_], ToEntityMarshaller[_]]
val um: mutable.Map[Class[_], FromEntityUnmarshaller[_]] = mutable.Map.empty[Class[_], FromEntityUnmarshaller[_]]
}
trait JsonToEntityMarshaller extends PredefinedToEntityMarshallers {
implicit def findMarshaller[T](implicit cTag: ClassTag[T]): ToEntityMarshaller[T] =
m.getOrElseUpdate(cTag.runtimeClass, genericMarshaller[T]).asInstanceOf[ToEntityMarshaller[T]]
def genericMarshaller[T]: ToEntityMarshaller[T] =
stringMarshaller(MediaTypes.`application/json`)
.compose[T](mapper.writeValueAsString)
}
trait JsonFromEntityUnmarshaller extends PredefinedFromEntityUnmarshallers {
implicit def findUnmarshaller[T](implicit cTag: ClassTag[T]): FromEntityUnmarshaller[T] =
um.getOrElseUpdate(cTag.runtimeClass, genericUnmarshaller[T](cTag)).asInstanceOf[FromEntityUnmarshaller[T]]
def genericUnmarshaller[T](cTag: ClassTag[T]): FromEntityUnmarshaller[T] =
stringUnmarshaller.forContentTypes(MediaTypes.`application/json`)
.map(mapper.readValue(_, cTag.runtimeClass).asInstanceOf[T])
}
开发者ID:ayush03agarwal,项目名称:connekt,代码行数:45,代码来源:JsonToEntityMarshaller.scala
示例16: JsonUtil
//设置package包名称以及导入依赖的类
package com.logicstack.util.json
import java.text.SimpleDateFormat
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter
import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper, PropertyNamingStrategy}
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
object JsonUtil {
private val dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZ"
private val filter = SimpleBeanPropertyFilter.serializeAllExcept()
private val javaTimeModule = new JavaTimeModule()
val CamelCaseMapper = new ObjectMapper() with ScalaObjectMapper
CamelCaseMapper.registerModules(DefaultScalaModule, javaTimeModule)
.setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false)
.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true)
.setDateFormat(new SimpleDateFormat(dateFormat))
val SnakeCaseMapper = new ObjectMapper() with ScalaObjectMapper
SnakeCaseMapper.registerModules(DefaultScalaModule, javaTimeModule)
.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false)
.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true)
.setDateFormat(new SimpleDateFormat(dateFormat))
}
开发者ID:crocker,项目名称:json-util,代码行数:33,代码来源:JsonUtil.scala
示例17: JacksonConverterScala
//设置package包名称以及导入依赖的类
package com.catinthedark.lib.network
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import scala.collection.mutable
class JacksonConverterScala(private val objectMapper: ObjectMapper = new ObjectMapper()) extends Converter {
objectMapper.registerModule(DefaultScalaModule)
private val converters = new mutable.HashMap[String, Map[String, Any] => Message]()
override def toJson(data: Message): String = {
val wrapper = Wrapper(data = data, className = data.getClass.getCanonicalName, sender = null)
objectMapper.writeValueAsString(wrapper)
}
override def fromJson(json: String): Wrapper = {
val wrapper = objectMapper.readValue(json, classOf[Wrapper])
val converter = converters.getOrElse(wrapper.className, throw new Exception(s"There is no ${wrapper.className} converter"))
val data = converter.apply(wrapper.data.asInstanceOf[Map[String, Message]])
wrapper.copy(data = data)
}
override def registerConverter[T](clazz: Class[T], converter: Map[String, Any] => Message): JacksonConverterScala = {
converters.put(clazz.getCanonicalName, converter)
this
}
override def registerMessage[T <: Message](clazz: Class[T]): JacksonConverterScala = {
registerConverter(clazz, (data) => {
defaultConverter(data, clazz)
})
}
private def defaultConverter[T <: Message](data: Map[String, Any], clazz: Class[T]): Message = {
objectMapper.convertValue(data, clazz)
}
def registeredConverters = converters.keySet
}
开发者ID:cat-in-the-dark,项目名称:old48_36_game,代码行数:42,代码来源:JacksonConverterScala.scala
示例18: Hello
//设置package包名称以及导入依赖的类
package com.example
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.{OptionModule, TupleModule, DefaultScalaModule}
object Hello {
case class Person(name: String, age: Int)
case class Organization(name: String, persons: List[Person])
def main(args: Array[String]): Unit = {
val json = """{"name":"some organization","persons":[{"name":"Taro","age":22},{"name":"Hanako","age":18},{"name":"Saburo","age":25}]} """
val organization =
Organization(
"some organization",
List(Person("Taro", 22), Person("Hanako", 18), Person("Saburo", 25))
)
val mapper = new ObjectMapper
mapper.registerModule(DefaultScalaModule)
println(json)
println(mapper.readValue(json, classOf[Organization]))
println(mapper.writeValueAsString(organization))
println("Hello, world!")
}
}
开发者ID:shigemk2,项目名称:my-jackson-module-scala-sample,代码行数:30,代码来源:Hello.scala
示例19: HelloSpec
//设置package包名称以及导入依赖的类
import com.example.Hello.{Organization, Person}
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import org.scalatest._
class HelloSpec extends FunSpec with Matchers {
describe("JacksonModule") {
it("parse json as Case Class") {
val json =
"""|{"name":"some organization",
| "persons":
| [{"name":"Taro","age":22},
| {"name":"Hanako","age":18},
| {"name":"Saburo","age":25}]}""".stripMargin
val mapper = new ObjectMapper
mapper.registerModule(DefaultScalaModule)
mapper.readValue(json, classOf[Organization]) should be(Organization("some organization",
List(Person("Taro", 22),
Person("Hanako", 18),
Person("Saburo", 25))))
}
}
it("parse json use Scala Collection") {
val json =
"""|{"name":"some organization",
| "persons":
| [{"name":"Taro","age":22},
| {"name":"Hanako","age":18},
| {"name":"Saburo","age":25}]}""".stripMargin
val mapper = new ObjectMapper
mapper.registerModule(DefaultScalaModule)
mapper.readValue(json, classOf[Map[_, _]]) should be {
Map("name" -> "some organization",
"persons" -> List(
Map("name" -> "Taro", "age" -> 22), Map("name" -> "Hanako", "age" -> 18), Map("name" -> "Saburo", "age" -> 25)
)
)
}
}
it("produce json from Scala Collection") {
val organization =
Map("name" -> "some organization",
"persons" -> List(
Map("name" -> "Taro", "age" -> 22), Map("name" -> "Hanako", "age" -> 18), Map("name" -> "Saburo", "age" -> 25)
)
)
val mapper = new ObjectMapper
mapper.registerModule(DefaultScalaModule)
mapper.writeValueAsString(organization) should be {
"""{"name":"some organization","persons":[{"name":"Taro","age":22},{"name":"Hanako","age":18},{"name":"Saburo","age":25}]}"""
}
}
}
开发者ID:shigemk2,项目名称:my-jackson-module-scala-sample,代码行数:62,代码来源:HelloSpec.scala
示例20: Serializer
//设置package包名称以及导入依赖的类
package reqeusts
import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import scala.reflect.ClassTag
object Serializer {
val mapper = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
mapper.registerModule(DefaultScalaModule)
val jsonWriter = mapper.writer()
def toObject[T : ClassTag](jsonString: String, clazz: Class[T]) : T = {
mapper.readValue(jsonString, clazz)
}
def toString(data : AnyRef) : String = {
jsonWriter.writeValueAsString(data)
}
}
开发者ID:liuhb86,项目名称:splendor-ai,代码行数:23,代码来源:Serializer.scala
注:本文中的com.fasterxml.jackson.module.scala.DefaultScalaModule类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论