本文整理汇总了Scala中com.fasterxml.jackson.core.JsonParser类的典型用法代码示例。如果您正苦于以下问题:Scala JsonParser类的具体用法?Scala JsonParser怎么用?Scala JsonParser使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了JsonParser类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: BulkItemResponseDeserializer
//设置package包名称以及导入依赖的类
package com.github.thanhtien522.eshttpclient.entities
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.{DeserializationContext, JsonDeserializer, JsonNode}
class BulkItemResponseDeserializer extends JsonDeserializer[BulkItemResponse] {
override def deserialize(p: JsonParser, ctxt: DeserializationContext): BulkItemResponse = {
val node = p.getCodec.readTree[JsonNode](p)
node.fieldNames().next() match {
case "index" => BulkItemResponse("index", p.getCodec.treeToValue(node.get("index"), classOf[IndexResponse]))
case "create" => BulkItemResponse("create", p.getCodec.treeToValue(node.get("create"), classOf[IndexResponse]))
case "update" => BulkItemResponse("update", p.getCodec.treeToValue(node.get("update"), classOf[UpdateResponse]))
case "delete" => BulkItemResponse("delete", p.getCodec.treeToValue(node.get("delete"), classOf[DeleteResponse]))
case s => throw new Exception("Deserialize BulkItemResponse failure. Unhandled action name `" + s + "`")
}
}
}
class ErrorDeserializer extends JsonDeserializer[Error] {
override def deserialize(p: JsonParser, ctxt: DeserializationContext): Error = {
val node = p.getCodec.readTree[JsonNode](p)
if (node.isTextual) {
Error("exception", node.asText(), null)
} else if (node.isObject) {
val `type` = node.get("type").asText()
val reason = node.get("reason").asText()
val caused = if (node.has("caused_by")) p.getCodec.treeToValue(node.get("caused_by"), classOf[Error]) else null
Error(`type`, reason, caused)
} else {
throw new Exception(s"Deserialize Error failure. Expected STRING or OBJECT, actual ${node.getNodeType.toString}")
}
}
}
开发者ID:thanhtien522,项目名称:es-http-client,代码行数:37,代码来源:Deserializers.scala
示例2: Channel
//设置package包名称以及导入依赖的类
package com.flipkart.connekt.commons.entities
import com.fasterxml.jackson.core.{JsonGenerator, JsonParser}
import com.fasterxml.jackson.databind.{DeserializationContext, JsonDeserializer, JsonSerializer, SerializerProvider}
object Channel extends Enumeration {
type Channel = Value
val PUSH = Value("push")
val EMAIL = Value("email")
val SMS = Value("sms")
val CARDS = Value("cards")
val OPENWEB = Value("openweb")
}
class ChannelToStringSerializer extends JsonSerializer[Channel.Value] {
override def serialize(t: Channel.Value, jsonGenerator: JsonGenerator, serializerProvider: SerializerProvider) = {
jsonGenerator.writeObject(t.toString)
}
}
class ChannelToStringDeserializer extends JsonDeserializer[Channel.Value] {
@Override
override def deserialize(parser:JsonParser, context:DeserializationContext):Channel.Value={
try {
com.flipkart.connekt.commons.entities.Channel.withName(parser.getValueAsString.toLowerCase)
} catch {
case e: NoSuchElementException =>
null
}
}
}
开发者ID:ayush03agarwal,项目名称:connekt,代码行数:32,代码来源:Channel.scala
示例3: SyncType
//设置package包名称以及导入依赖的类
package com.flipkart.connekt.commons.sync
import com.fasterxml.jackson.core.{JsonGenerator, JsonParser}
import com.fasterxml.jackson.databind.{DeserializationContext, JsonDeserializer, JsonSerializer, SerializerProvider}
object SyncType extends Enumeration {
type SyncType = Value
val CLIENT_ADD,TEMPLATE_CHANGE, AUTH_CHANGE, STENCIL_CHANGE, STENCIL_FABRIC_CHANGE,
STENCIL_COMPONENTS_UPDATE, CLIENT_QUEUE_CREATE, SUBSCRIPTION, USER_PROJECT_CONFIG_CHANGE = Value
}
class SyncTypeToStringSerializer extends JsonSerializer[SyncType.Value] {
override def serialize(t: SyncType.Value, jsonGenerator: JsonGenerator, serializerProvider: SerializerProvider) = {
jsonGenerator.writeObject(t.toString)
}
}
class SyncTypeToStringDeserializer extends JsonDeserializer[SyncType.Value] {
@Override
override def deserialize(parser: JsonParser, context: DeserializationContext): SyncType.Value = {
try {
SyncType.withName(parser.getValueAsString.toUpperCase)
} catch {
case e: NoSuchElementException =>
null
}
}
}
开发者ID:ayush03agarwal,项目名称:connekt,代码行数:30,代码来源:SyncType.scala
示例4: MessageReader
//设置package包名称以及导入依赖的类
package com.hypertino.hyperbus.serialization
import java.io.{Reader, StringReader}
import com.fasterxml.jackson.core.{JsonFactory, JsonParser}
import com.hypertino.binders.json.{JacksonParserAdapter, JsonBindersFactory}
import com.hypertino.binders.value.{Obj, Text, Value}
import com.hypertino.hyperbus.model.{Body, Header, Headers, HeadersMap, Message}
object MessageReader {
def read[M <: Message[_ <: Body,_ <: Headers]](reader: Reader, concreteDeserializer: MessageDeserializer[M]): M = {
val jacksonFactory = new JsonFactory()
jacksonFactory.disable(JsonParser.Feature.AUTO_CLOSE_SOURCE)
val jp = jacksonFactory.createParser(reader)
val headers = try {
val adapter = new JacksonParserAdapter(jp)
val headers = JsonBindersFactory.findFactory().withJsonParserApi(adapter) { jpa ?
val headersSeq = jpa.unbind[Value].asInstanceOf[Obj].v.toSeq // todo: this isn't great, also see https://github.com/hypertino/binders/issues/2
val transformedSeq = headersSeq.map {
case (Header.CONTENT_TYPE, value) ? Header.CONTENT_TYPE ? JsonContentTypeConverter.universalJsonContentTypeToSimple(value)
case other ? other
}
HeadersMap(transformedSeq: _*)
}
jp.nextToken()
val offset = jp.getTokenLocation.getCharOffset
reader.reset()
reader.skip(offset)
headers
}
finally {
jp.close()
}
concreteDeserializer(reader, headers)
}
def fromString[M <: Message[_ <: Body,_ <: Headers]](message: String, concreteDeserializer: MessageDeserializer[M]): M = {
val stringReader = new StringReader(message)
try {
read(stringReader, concreteDeserializer)
}
finally {
stringReader.close()
}
}
}
开发者ID:hypertino,项目名称:hyperbus,代码行数:52,代码来源:MessageReader.scala
示例5: Json
//设置package包名称以及导入依赖的类
package com.amarjanica.discourse.util
import java.time._
import com.fasterxml.jackson.core.{JsonParser, JsonGenerator}
import com.fasterxml.jackson.databind._
import com.fasterxml.jackson.databind.DeserializationFeature._
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.module.scala.DefaultScalaModule
object Json {
private val jtstampSerializer = new JsonSerializer[java.time.OffsetDateTime] {
override def serialize(value: java.time.OffsetDateTime, generator: JsonGenerator, x: SerializerProvider) =
generator.writeString(value.toString())
}
private val jtstampDeserializer = new JsonDeserializer[java.time.OffsetDateTime] {
override def deserialize(parser: JsonParser, context: DeserializationContext) =
OffsetDateTime.parse(parser.getValueAsString)
}
val timeModule = new SimpleModule()
.addSerializer(classOf[java.time.OffsetDateTime], jtstampSerializer)
.addDeserializer(classOf[java.time.OffsetDateTime], jtstampDeserializer)
val mapper = {
val o = new ObjectMapper()
o.registerModule(DefaultScalaModule)
o.registerModule(timeModule)
o.configure(FAIL_ON_UNKNOWN_PROPERTIES, false)
o
}
}
开发者ID:amarjanica,项目名称:discourse-scala-client,代码行数:31,代码来源:Json.scala
示例6: JacksonSupport
//设置package包名称以及导入依赖的类
package io.eels.util
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
object JacksonSupport {
val mapper: ObjectMapper with ScalaObjectMapper = new ObjectMapper with ScalaObjectMapper
mapper.registerModule(DefaultScalaModule)
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false)
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true)
mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true)
}
开发者ID:51zero,项目名称:eel-sdk,代码行数:21,代码来源:JacksonSupport.scala
示例7: WorksIncludes
//设置package包名称以及导入依赖的类
package uk.ac.wellcome.platform.api.models
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.databind.{
DeserializationContext,
JsonDeserializer,
JsonMappingException
}
case class WorksIncludes(identifiers: Boolean = false)
class WorksIncludesParsingException(msg: String)
extends JsonMappingException(msg: String)
case object WorksIncludes {
val recognisedIncludes = List("identifiers")
/// Parse an ?includes query-parameter string.
///
/// If any unexpected includes are spotted, we raise an
/// `WorksIncludesParsingException`.
def apply(queryParam: String): WorksIncludes = {
val includesList = queryParam.split(",").toList
val unrecognisedIncludes = includesList
.filterNot(recognisedIncludes.contains)
if (unrecognisedIncludes.length == 0) {
WorksIncludes(
identifiers = includesList.contains("identifiers")
)
} else {
val errorMessage = if (unrecognisedIncludes.length == 1) {
s"'${unrecognisedIncludes.head}' is not a valid include"
} else {
s"${unrecognisedIncludes.mkString("'", "', '", "'")} are not valid includes"
}
throw new WorksIncludesParsingException(errorMessage)
}
}
def apply(queryParam: Option[String]): WorksIncludes =
queryParam match {
case Some(s) => WorksIncludes(s)
case None => WorksIncludes()
}
}
class WorksIncludesDeserializer extends JsonDeserializer[WorksIncludes] {
override def deserialize(p: JsonParser,
ctxt: DeserializationContext): WorksIncludes =
WorksIncludes(p.getText())
}
class WorksIncludesDeserializerModule extends SimpleModule {
addDeserializer(classOf[WorksIncludes], new WorksIncludesDeserializer())
}
开发者ID:wellcometrust,项目名称:platform-api,代码行数:58,代码来源:WorksIncludes.scala
示例8: DtabCodec
//设置package包名称以及导入依赖的类
package io.buoyant.namerd
import com.fasterxml.jackson.core.{JsonGenerator, JsonParser}
import com.fasterxml.jackson.databind.{DeserializationContext, JsonDeserializer, JsonSerializer, SerializerProvider}
import com.fasterxml.jackson.databind.module.SimpleModule
import com.twitter.finagle.{Dentry, NameTree, Path}
object DtabCodec {
def module = {
val module = new SimpleModule
module.addSerializer(classOf[Path], new JsonSerializer[Path] {
override def serialize(path: Path, json: JsonGenerator, p: SerializerProvider): Unit =
json.writeString(path.show)
})
module.addDeserializer(classOf[Path], new JsonDeserializer[Path] {
override def deserialize(json: JsonParser, ctx: DeserializationContext) =
Path.read(json.getValueAsString)
})
module.addSerializer(classOf[Dentry.Prefix], new JsonSerializer[Dentry.Prefix] {
override def serialize(pfx: Dentry.Prefix, json: JsonGenerator, p: SerializerProvider) {
json.writeString(pfx.show)
}
})
module.addDeserializer(classOf[Dentry.Prefix], new JsonDeserializer[Dentry.Prefix] {
override def deserialize(json: JsonParser, ctx: DeserializationContext) =
Dentry.Prefix.read(json.getValueAsString)
})
module.addSerializer(classOf[NameTree[Path]], new JsonSerializer[NameTree[Path]] {
override def serialize(
nameTree: NameTree[Path],
json: JsonGenerator,
p: SerializerProvider
): Unit = json.writeString(nameTree.show)
})
module.addDeserializer(classOf[NameTree[Path]], new JsonDeserializer[NameTree[Path]] {
override def deserialize(json: JsonParser, ctx: DeserializationContext) =
NameTree.read(json.getValueAsString)
})
module
}
}
开发者ID:linkerd,项目名称:linkerd,代码行数:47,代码来源:DtabCodec.scala
示例9: factory
//设置package包名称以及导入依赖的类
package io.buoyant.config.types
import com.fasterxml.jackson.core.{JsonGenerator, JsonParser}
import com.fasterxml.jackson.databind.{DeserializationContext, SerializerProvider}
import com.twitter.finagle.thrift.Protocols
import io.buoyant.config.{ConfigDeserializer, ConfigSerializer}
import org.apache.thrift.protocol.{TCompactProtocol, TProtocolFactory}
sealed trait ThriftProtocol {
def factory: TProtocolFactory
def name: String
}
object ThriftProtocol {
object Binary extends ThriftProtocol {
def factory = Protocols.binaryFactory()
val name = "binary"
}
object Compact extends ThriftProtocol {
def factory = new TCompactProtocol.Factory
val name = "compact"
}
}
class ThriftProtocolDeserializer extends ConfigDeserializer[ThriftProtocol] {
override def deserialize(jp: JsonParser, ctxt: DeserializationContext): ThriftProtocol =
catchMappingException(ctxt) {
_parseString(jp, ctxt) match {
case "binary" => ThriftProtocol.Binary
case "compact" => ThriftProtocol.Compact
case protocol =>
throw new IllegalArgumentException(s"unsupported thrift protocol $protocol")
}
}
}
class ThriftProtocolSerializer extends ConfigSerializer[ThriftProtocol] {
override def serialize(
value: ThriftProtocol,
jgen: JsonGenerator,
provider: SerializerProvider
): Unit = jgen.writeString(value.name)
}
开发者ID:linkerd,项目名称:linkerd,代码行数:43,代码来源:ThriftProtocolDeserializer.scala
示例10: PathDeserializer
//设置package包名称以及导入依赖的类
package io.buoyant.config.types
import com.fasterxml.jackson.core.{JsonGenerator, JsonParser}
import com.fasterxml.jackson.databind.{SerializerProvider, DeserializationContext}
import com.twitter.finagle.Path
import io.buoyant.config.{ConfigSerializer, ConfigDeserializer}
class PathDeserializer extends ConfigDeserializer[Path] {
override def deserialize(jp: JsonParser, ctxt: DeserializationContext): Path =
catchMappingException(ctxt) {
Path.read(_parseString(jp, ctxt))
}
}
class PathSerializer extends ConfigSerializer[Path] {
override def serialize(
value: Path,
jgen: JsonGenerator,
provider: SerializerProvider
): Unit = jgen.writeString(value.show)
}
开发者ID:linkerd,项目名称:linkerd,代码行数:22,代码来源:PathDeserializer.scala
示例11: InetAddressDeserializer
//设置package包名称以及导入依赖的类
package io.buoyant.config.types
import com.fasterxml.jackson.core.{JsonGenerator, JsonParser}
import com.fasterxml.jackson.databind.{SerializerProvider, DeserializationContext}
import com.google.common.net.InetAddresses
import io.buoyant.config.{ConfigSerializer, ConfigDeserializer}
import java.net.InetAddress
class InetAddressDeserializer extends ConfigDeserializer[InetAddress] {
override def deserialize(jp: JsonParser, ctxt: DeserializationContext): InetAddress =
catchMappingException(ctxt) {
InetAddresses.forString(_parseString(jp, ctxt))
}
}
class InetAddressSerializer extends ConfigSerializer[InetAddress] {
override def serialize(
value: InetAddress,
jgen: JsonGenerator,
provider: SerializerProvider
): Unit = jgen.writeString(value.getHostName)
}
开发者ID:linkerd,项目名称:linkerd,代码行数:23,代码来源:InetAddressDeserializer.scala
示例12: Directory
//设置package包名称以及导入依赖的类
package io.buoyant.config.types
import com.fasterxml.jackson.core.{JsonGenerator, JsonParser}
import com.fasterxml.jackson.databind.{SerializerProvider, DeserializationContext}
import io.buoyant.config.{ConfigSerializer, ConfigDeserializer}
import java.nio.file.Paths
case class Directory(path: java.nio.file.Path) {
require(path.toFile.isDirectory, s"$path is not a directory")
}
class DirectoryDeserializer extends ConfigDeserializer[Directory] {
override def deserialize(jp: JsonParser, ctxt: DeserializationContext): Directory =
catchMappingException(ctxt) {
Directory(Paths.get(_parseString(jp, ctxt)))
}
}
class DirectorySerializer extends ConfigSerializer[Directory] {
override def serialize(
value: Directory,
jgen: JsonGenerator,
provider: SerializerProvider
): Unit = jgen.writeString(value.path.toString)
}
开发者ID:linkerd,项目名称:linkerd,代码行数:26,代码来源:DirectoryDeserializer.scala
示例13: Port
//设置package包名称以及导入依赖的类
package io.buoyant.config.types
import com.fasterxml.jackson.core.{JsonGenerator, JsonParser}
import com.fasterxml.jackson.databind.{SerializerProvider, DeserializationContext}
import io.buoyant.config.{ConfigSerializer, ConfigDeserializer}
case class Port(port: Int) {
val MinValue = 0
val MaxValue = math.pow(2, 16) - 1
require((MinValue <= port) && (port <= MaxValue), s"$port outside valid range for ports")
}
class PortDeserializer extends ConfigDeserializer[Port] {
override def deserialize(jp: JsonParser, ctxt: DeserializationContext): Port =
catchMappingException(ctxt) {
Port(_parseInteger(jp, ctxt))
}
}
class PortSerializer extends ConfigSerializer[Port] {
override def serialize(
value: Port,
jgen: JsonGenerator,
provider: SerializerProvider
): Unit = jgen.writeNumber(value.port)
}
开发者ID:linkerd,项目名称:linkerd,代码行数:27,代码来源:PortDeserializer.scala
示例14: LogLevelDeserializer
//设置package包名称以及导入依赖的类
package io.buoyant.config.types
import com.fasterxml.jackson.core.{JsonGenerator, JsonParser}
import com.fasterxml.jackson.databind.{SerializerProvider, DeserializationContext}
import com.twitter.logging.Level
import io.buoyant.config.{ConfigSerializer, ConfigDeserializer}
class LogLevelDeserializer extends ConfigDeserializer[Level] {
override def deserialize(jp: JsonParser, ctxt: DeserializationContext): Level =
catchMappingException(ctxt) {
val lname = _parseString(jp, ctxt)
Level.parse(lname.toUpperCase).getOrElse {
throw new IllegalArgumentException(s"Illegal log level: $lname")
}
}
}
class LogLevelSerializer extends ConfigSerializer[Level] {
override def serialize(
level: Level,
jgen: JsonGenerator,
provider: SerializerProvider
): Unit = jgen.writeString(level.name)
}
开发者ID:linkerd,项目名称:linkerd,代码行数:26,代码来源:LogLevelDeserializer.scala
示例15: DtabDeserializer
//设置package包名称以及导入依赖的类
package io.buoyant.config.types
import com.fasterxml.jackson.core.{JsonGenerator, JsonParser}
import com.fasterxml.jackson.databind.{SerializerProvider, DeserializationContext}
import com.twitter.finagle.Dtab
import io.buoyant.config.{ConfigSerializer, ConfigDeserializer}
class DtabDeserializer extends ConfigDeserializer[Dtab] {
override def deserialize(parser: JsonParser, ctx: DeserializationContext): Dtab =
catchMappingException(ctx) {
Dtab.read(_parseString(parser, ctx))
}
}
class DtabSerializer extends ConfigSerializer[Dtab] {
override def serialize(
value: Dtab,
jgen: JsonGenerator,
provider: SerializerProvider
): Unit = jgen.writeString(value.show)
}
开发者ID:linkerd,项目名称:linkerd,代码行数:22,代码来源:DtabDeserializer.scala
示例16: File
//设置package包名称以及导入依赖的类
package io.buoyant.config.types
import com.fasterxml.jackson.core.{JsonGenerator, JsonParser}
import com.fasterxml.jackson.databind.{SerializerProvider, DeserializationContext}
import io.buoyant.config.{ConfigSerializer, ConfigDeserializer}
import java.nio.file.Paths
case class File(path: java.nio.file.Path) {
require(path.toFile.isFile, s"$path is not a file")
}
class FileDeserializer extends ConfigDeserializer[File] {
override def deserialize(jp: JsonParser, ctxt: DeserializationContext): File =
catchMappingException(ctxt) {
File(Paths.get(_parseString(jp, ctxt)))
}
}
class FileSerializer extends ConfigSerializer[File] {
override def serialize(
value: File,
jgen: JsonGenerator,
provider: SerializerProvider
): Unit = jgen.writeString(value.path.toString)
}
开发者ID:linkerd,项目名称:linkerd,代码行数:26,代码来源:FileDeserializer.scala
示例17: PathMatcherDeserializer
//设置package包名称以及导入依赖的类
package io.buoyant.config.types
import com.fasterxml.jackson.core.{JsonGenerator, JsonParser}
import com.fasterxml.jackson.databind.{SerializerProvider, DeserializationContext}
import com.twitter.finagle.buoyant.PathMatcher
import io.buoyant.config.{ConfigSerializer, ConfigDeserializer}
class PathMatcherDeserializer extends ConfigDeserializer[PathMatcher] {
override def deserialize(jp: JsonParser, ctxt: DeserializationContext): PathMatcher =
catchMappingException(ctxt) {
PathMatcher(_parseString(jp, ctxt))
}
}
class PathMatcherSerializer extends ConfigSerializer[PathMatcher] {
override def serialize(
value: PathMatcher,
jgen: JsonGenerator,
provider: SerializerProvider
): Unit = jgen.writeString(value.toString)
}
开发者ID:linkerd,项目名称:linkerd,代码行数:22,代码来源:PathMatcherDeserializer.scala
示例18: ScalaDbEnumSerializers
//设置package包名称以及导入依赖的类
package webby.commons.io.jackson
import java.io.IOException
import com.fasterxml.jackson.core.{JsonGenerator, JsonParser}
import com.fasterxml.jackson.databind._
import com.fasterxml.jackson.databind.deser.Deserializers
import com.fasterxml.jackson.databind.ser.Serializers
import com.fasterxml.jackson.module.scala.JacksonModule
import querio.{AnyScalaDbEnum, AnyScalaDbEnumCls, _}
private object ScalaDbEnumSerializers extends Serializers.Base {
override def findSerializer(config: SerializationConfig, javaType: JavaType, beanDesc: BeanDescription): JsonSerializer[_] = {
if (classOf[AnyScalaDbEnumCls].isAssignableFrom(javaType.getRawClass)) ScalaDbEnumSerializer
else null
}
}
private object ScalaDbEnumSerializer extends JsonSerializer[AnyScalaDbEnumCls] {
def serialize(value: AnyScalaDbEnumCls, jgen: JsonGenerator, provider: SerializerProvider) {
jgen.writeString(value.getDbValue)
}
}
private object ScalaDbEnumDeserializers extends Deserializers.Base {
override def findBeanDeserializer(javaType: JavaType, config: DeserializationConfig, beanDesc: BeanDescription): JsonDeserializer[_] = {
if (classOf[AnyScalaDbEnumCls].isAssignableFrom(javaType.getRawClass)) {
ScalaDbEnums.getEnum(javaType.getRawClass.asInstanceOf[Class[AnyScalaDbEnumCls]]) match {
case Some(enum) => new ScalaDbEnumDeserializer(enum)
case None => null
}
} else null
}
}
private class ScalaDbEnumDeserializer(enum: AnyScalaDbEnum) extends JsonDeserializer[AnyScalaDbEnumCls] {
override def deserialize(jp: JsonParser, ctxt: DeserializationContext): AnyScalaDbEnumCls = {
enum.getValue(jp.getValueAsString) match {
case Some(e) => e
case None => throw new IOException(s"Invalid enum value '${jp.getValueAsString}'")
}
}
}
trait ScalaDbEnumJacksonModule extends JacksonModule {
this += ScalaDbEnumSerializers
this += ScalaDbEnumDeserializers
}
开发者ID:citrum,项目名称:webby,代码行数:52,代码来源:ScalaDbEnumJacksonModule.scala
示例19: DbEnumSerializers
//设置package包名称以及导入依赖的类
package webby.commons.io.jackson
import java.io.IOException
import com.fasterxml.jackson.core.{JsonGenerator, JsonParser}
import com.fasterxml.jackson.databind._
import com.fasterxml.jackson.databind.deser.Deserializers
import com.fasterxml.jackson.databind.ser.Serializers
import com.fasterxml.jackson.module.scala.JacksonModule
import querio._
// ------------------------------- Serializers -------------------------------
private object DbEnumSerializers extends Serializers.Base {
override def findSerializer(config: SerializationConfig, javaType: JavaType, beanDesc: BeanDescription): JsonSerializer[_] = {
if (classOf[DbEnum#Cls].isAssignableFrom(javaType.getRawClass)) DbEnumSerializer
else null
}
}
private object DbEnumSerializer extends JsonSerializer[DbEnum#Cls] {
def serialize(value: DbEnum#Cls, jgen: JsonGenerator, provider: SerializerProvider) {
jgen.writeNumber(value.getId)
}
}
// ------------------------------- Deserializers -------------------------------
private object DbEnumDeserializers extends Deserializers.Base {
override def findBeanDeserializer(javaType: JavaType, config: DeserializationConfig, beanDesc: BeanDescription): JsonDeserializer[_] = {
if (classOf[DbEnum#Cls].isAssignableFrom(javaType.getRawClass)) {
DbEnums.getEnum(javaType.getRawClass.asInstanceOf[Class[DbEnum#Cls]]) match {
case Some(enum) => new DbEnumDeserializer(enum)
case None => null
}
} else null
}
}
private class DbEnumDeserializer(enum: DbEnum) extends JsonDeserializer[DbEnum#Cls] {
override def deserialize(jp: JsonParser, ctxt: DeserializationContext): DbEnum#Cls = {
enum.getValue(jp.getValueAsInt) match {
case Some(e) => e
case None => throw new IOException(s"Invalid enum value '${jp.getValueAsInt}' for " + enum.getClass.getName)
}
}
}
// ------------------------------- Module -------------------------------
trait DbEnumJacksonModule extends JacksonModule {
this += DbEnumSerializers
this += DbEnumDeserializers
}
开发者ID:citrum,项目名称:webby,代码行数:55,代码来源:DbEnumJacksonModule.scala
示例20: CustomBigDecimalDeserialiserModule
//设置package包名称以及导入依赖的类
package cjp.catalogue.conf
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.core.{JsonToken, JsonParseException, JsonParser}
import com.fasterxml.jackson.databind.{DeserializationContext}
import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer
import scala.util.{Failure, Success, Try}
class CustomBigDecimalDeserialiserModule extends SimpleModule("CustomBigDecimalDeserialiserModule") {
addDeserializer(classOf[BigDecimal], BigDecimalDeserializer)
}
object BigDecimalDeserializer extends StdScalarDeserializer[BigDecimal](classOf[BigDecimal]) {
override def deserialize(jsonParser: JsonParser, context: DeserializationContext): BigDecimal = {
Option(jsonParser.getValueAsString) match {
case Some(str: String) => Try(BigDecimal(str)) match {
case Success(value) => value
case Failure(error) => throw new JsonParseException(s"Unable to parse ${str} to BigDecimal", jsonParser.getCurrentLocation, error)
}
case None if jsonParser.getCurrentToken == JsonToken.VALUE_NULL => null.asInstanceOf[BigDecimal]
case _ => throw new JsonParseException(s"Expected a string token representing type 'BigDecimal', found: ${jsonParser.getCurrentToken}", jsonParser.getCurrentLocation)
}
}
}
开发者ID:UKHomeOffice,项目名称:product-catalogue,代码行数:26,代码来源:CustomBigDecimalSerialiserModule.scala
注:本文中的com.fasterxml.jackson.core.JsonParser类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论