• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala JsonGenerator类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中com.fasterxml.jackson.core.JsonGenerator的典型用法代码示例。如果您正苦于以下问题:Scala JsonGenerator类的具体用法?Scala JsonGenerator怎么用?Scala JsonGenerator使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了JsonGenerator类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: CirceJsonSerializer

//设置package包名称以及导入依赖的类
package io.circe.jackson

import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.databind.{ JsonSerializer, SerializerProvider }
import io.circe.{ Json, JsonBigDecimal, JsonBiggerDecimal, JsonDecimal, JsonDouble, JsonFloat, JsonLong }

private[jackson] final object CirceJsonSerializer extends JsonSerializer[Json] {
  import java.math.{ BigDecimal => JBigDecimal, BigInteger }
  import com.fasterxml.jackson.databind.node.{ BigIntegerNode, DecimalNode }

  override final def serialize(
    value: Json,
    json: JsonGenerator,
    provider: SerializerProvider
  ): Unit = value match {
    case Json.JNumber(v) => v match {
      case JsonLong(x) => json.writeNumber(x)
      case JsonDouble(x) => json.writeNumber(x)
      case JsonFloat(x) => json.writeNumber(x)
      case JsonDecimal(x) => json.writeString(x)
      case JsonBiggerDecimal(x) => json.writeString(x.toString)
      case JsonBigDecimal(x) =>
        // Workaround #3784: Same behaviour as if JsonGenerator were
        // configured with WRITE_BIGDECIMAL_AS_PLAIN, but forced as this
        // configuration is ignored when called from ObjectMapper.valueToTree
        val raw = x.bigDecimal.stripTrailingZeros.toPlainString

        if (raw contains ".") json.writeTree(new DecimalNode(new JBigDecimal(raw)))
          else json.writeTree(new BigIntegerNode(new BigInteger(raw)))
    }
    case Json.JString(v) => json.writeString(v)
    case Json.JBoolean(v) => json.writeBoolean(v)
    case Json.JArray(elements) => {
      json.writeStartArray()
      elements.foreach { t => serialize(t, json, provider) }
      json.writeEndArray()
    }
    case Json.JObject(values) => {
      json.writeStartObject()
      values.toList.foreach { t =>
        json.writeFieldName(t._1)
        serialize(t._2, json, provider)
      }
      json.writeEndObject()
    }
    case Json.JNull => json.writeNull()
  }
} 
开发者ID:circe,项目名称:circe-jackson,代码行数:49,代码来源:CirceJsonSerializer.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: SortedObjectSerializer

//设置package包名称以及导入依赖的类
package io.mediachain.util

import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.databind.Module.SetupContext
import com.fasterxml.jackson.databind._
import com.fasterxml.jackson.databind.ser.Serializers
import org.json4s._
import org.json4s.jackson.Json4sScalaModule

class SortedObjectSerializer extends JsonSerializer[JValue]{
  def serialize(value: JValue, json: JsonGenerator, provider: SerializerProvider) {
    if (value == null) {
      json.writeNull()
    } else {
      value match {
        case JInt(v) => json.writeNumber(v.bigInteger)
        case JLong(v) => json.writeNumber(v)
        case JDouble(v) => json.writeNumber(v)
        case JDecimal(v) => json.writeNumber(v.bigDecimal)
        case JString(v) => json.writeString(v)
        case JBool(v) => json.writeBoolean(v)
        case JArray(elements) =>
          json.writeStartArray()
          elements filterNot (_ == JNothing) foreach (x => serialize(x, json, provider))
          json.writeEndArray()

        case JObject(fields) => {
          json.writeStartObject()
          fields sortWith { (f1, f2) =>
            f1._1.compareTo(f2._1) < 0
          } filterNot (_._2 == JNothing) foreach {
            case (n, v) =>
              json.writeFieldName(n)
              serialize(v, json, provider)
          }
          json.writeEndObject()
        }
        case JNull => json.writeNull()
        case JNothing => ()
      }
    }
  }

  override def isEmpty(value: JValue): Boolean = value == JNothing
}

private object SortedObjectSerializerResolver extends Serializers.Base {
  private val JVALUE = classOf[JValue]
  override def findSerializer(config: SerializationConfig, theType: JavaType, beanDesc: BeanDescription) = {
    if (!JVALUE.isAssignableFrom(theType.getRawClass)) null
    else new SortedObjectSerializer
  }
}


class Json4sWithSortedObjectsScalaModule extends Json4sScalaModule {
  override def setupModule(ctxt: SetupContext) {
    super.setupModule(ctxt)
    ctxt.addSerializers(SortedObjectSerializerResolver)
  }
} 
开发者ID:mediachain,项目名称:L-SPACE,代码行数:62,代码来源:SortedObjectSerializer.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: LocalDateSerializer

//设置package包名称以及导入依赖的类
package com.buysomegames.kernel

import java.time.LocalDate
import java.time.format.DateTimeFormatter

import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.databind.{JsonSerializer, SerializerProvider}
import com.twitter.finatra.json.modules.FinatraJacksonModule
import org.bson.types.ObjectId

private class LocalDateSerializer extends JsonSerializer[LocalDate] {
  override def serialize(value: LocalDate, gen: JsonGenerator, serializers: SerializerProvider): Unit = {
    gen.writeString(value.format(DateTimeFormatter.ISO_DATE))
  }
}

private class ObjectIdSerializer extends JsonSerializer[ObjectId] {
  override def serialize(value: ObjectId, gen: JsonGenerator, serializers: SerializerProvider): Unit = {
    gen.writeString(value.toHexString)
  }
}

object BuysomegamesJacksonModule extends FinatraJacksonModule {
  override val additionalJacksonModules = Seq(
    new SimpleModule {
      addSerializer(classOf[LocalDate], new LocalDateSerializer)
    },
    new SimpleModule {
      addSerializer(classOf[ObjectId], new ObjectIdSerializer)
    }
  )
} 
开发者ID:kaliy,项目名称:buysomegames,代码行数:34,代码来源:BuysomegamesJacksonModule.scala


示例7: 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


示例8: 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


示例9: 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


示例10: 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


示例11: 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


示例12: 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


示例13: 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


示例14: 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


示例15: 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


示例16: 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


示例17: 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


示例18: 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


示例19: JsonSerializer

//设置package包名称以及导入依赖的类
package com.martinsnyder.json

import com.fasterxml.jackson.core.{ JsonParser, JsonGenerator }
import com.fasterxml.jackson.databind.{ JsonSerializer => JacksonJsonSerializer, ObjectMapper, DeserializationContext, JsonDeserializer, SerializerProvider }
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.datatype.joda.JodaModule
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.martinsnyder.api.{ ApiLink, ResourceId }
import com.martinsnyder.util.TracedResult

object JsonSerializer {
  
    class LinkSerializer extends JacksonJsonSerializer[ApiLink] {
      override def handledType: Class[ApiLink] = classOf[ApiLink]

      override def serialize(link: ApiLink, generator: JsonGenerator, provider: SerializerProvider) {
        // Bind the trace to the parent threadLocal object
        val transformedLink = linkTransformer.transform(link)
        TracedResult.threadLocal.process(_ => transformedLink)

        // Serialize the object if we have one
        transformedLink.value.foreach(l => provider.defaultSerializeValue(l, generator))
      }
    }

    addSerializer(new LinkSerializer)
  }
}

class JsonSerializer(linkTransformer: LinkTransformer) {
  import JsonSerializer._

  private val objectMapper =
    new ObjectMapper()
      .registerModule(new JodaModule())
      .registerModule(DefaultScalaModule)
      .registerModule(ResourceIdSerializationModule)
      .registerModule(new LinkSerializationModule(linkTransformer))

  def toJson(value: AnyRef): TracedResult[String] =
    TracedResult.threadLocal.mount(objectMapper.writeValueAsString(value))

  def fromJson[T](json: String, toClass: Class[T]): TracedResult[T] =
    TracedResult.threadLocal.mount(objectMapper.readValue(json, toClass))
} 
开发者ID:MartinSnyder,项目名称:mrp,代码行数:46,代码来源:JsonSerializer.scala


示例20: PolymorphicSerializer

//设置package包名称以及导入依赖的类
package com.sk.app.proxmock.toolset.serialization.betterpolymorphism

import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.databind.{JsonSerializer, SerializerProvider}


private[betterpolymorphism] class PolymorphicSerializer(defaultSerializer: JsonSerializer[Object]) extends JsonSerializer[Object] {

   override def serialize(value: Object, gen: JsonGenerator, serializers: SerializerProvider): Unit = {
     val nameOption = JsonSubTypesUtil.asMapInverted(value.getClass).get(value.getClass)

     nameOption match {
       case Some(name) =>
         gen.writeStartObject()
         gen.writeFieldName(name)
         defaultSerializer.serialize(value, gen, serializers)
         gen.writeEndObject()

       case None =>
         defaultSerializer.serialize(value, gen, serializers)
     }
   }
 } 
开发者ID:szymonkudzia,项目名称:proxmock,代码行数:24,代码来源:PolymorphicSerializer.scala



注:本文中的com.fasterxml.jackson.core.JsonGenerator类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala StandardCopyOption类代码示例发布时间:2022-05-23
下一篇:
Scala HikariConfig类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap