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

Scala CustomSerializer类代码示例

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

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



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

示例1: JsonExtraction

//设置package包名称以及导入依赖的类
package uk.gov.hmrc.utils.json

import java.net.{URI, URL}

import org.json4s.JsonAST.JString
import org.json4s.jackson.JsonMethods.parse
import org.json4s.{CustomSerializer, DefaultFormats, Formats, JNull}

object JsonExtraction {

  val formats = DefaultFormats + json4sDateTimeSerializer + json4sLocalDateSerializer + UriSerializer + UrlSerializer + Json4sIntToBigDecimalSerializer

  def apply[A](body: String)(implicit m: Manifest[A], formats: Formats = formats): A = extractResponse[A](body)

  private def extractResponse[A](body: String)(implicit m: Manifest[A], format: Formats = formats): A = Option(body) match {
    case Some(b) if b.length > 0 =>
      try {
        parse(b, useBigDecimalForDouble = true).extract
      } catch {
        case t: Throwable =>
          throw t
      }
    case _ => throw new IllegalArgumentException("A string value is required for transformation")
  }

  case object UriSerializer extends CustomSerializer[URI](format => ( {
    case JString(uri) => URI.create(uri)
    case JNull => null
  }, {
    case uri: URI => JString(uri.toString)
  }
  ))

  case object UrlSerializer extends CustomSerializer[URL](format => ( {
    case JString(url) => new URL(url)
    case JNull => null
  }, {
    case url: URL => JString(url.toString)
  }
  ))

} 
开发者ID:danewatts,项目名称:zap-automation,代码行数:43,代码来源:JsonExtraction.scala


示例2: UuidSerializer

//设置package包名称以及导入依赖的类
package org.goingok.data.persistence.db.postgresql

import java.time.OffsetDateTime
import java.util.UUID

import org.json4s.JsonAST.JString
import org.json4s.{CustomSerializer, _}


object UuidSerializer extends CustomSerializer[UUID](format =>
  (
    {
      case JString(s) => UUID.fromString(s)
      case JNull => null
    },
    {
      case x: UUID => JString(x.toString)
    }
  )
)

object OffsetDateTimeSerializer extends CustomSerializer[OffsetDateTime](format => (
  {
    case JString(s) => OffsetDateTime.parse(s)
    case JNull => null
  },
  {
    case o:OffsetDateTime => JString(o.toString)
  }
)
) 
开发者ID:GoingOK,项目名称:goingok-server,代码行数:32,代码来源:CustomSerialisers.scala


示例3: DecompileLayoutSerializer

//设置package包名称以及导入依赖的类
package org.argus.amandroid.serialization

import org.argus.amandroid.core.decompile.DecompileLayout
import org.argus.jawa.core.util.{FileResourceUri, ISet}
import org.json4s.{CustomSerializer, Extraction, JValue}
import org.json4s.JsonDSL._


object DecompileLayoutSerializer extends CustomSerializer[DecompileLayout](format => (
  {
    case jv: JValue =>
      implicit val formats = format
      val outputUri  = (jv \ "outputUri").extract[FileResourceUri]
      val createFolder = (jv \ "createFolder").extract[Boolean]
      val srcFolder = (jv \ "srcFolder").extract[String]
      val libFolder = (jv \ "libFolder").extract[String]
      val createSeparateFolderForDexes = (jv \ "createSeparateFolderForDexes").extract[Boolean]
      val pkg = (jv \ "pkg").extract[String]
      val outputSrcUri = (jv \ "outputSrcUri").extract[FileResourceUri]
      val sourceFolders = (jv \ "sourceFolders").extract[ISet[String]]
      val libFolders = (jv \ "libFolders").extract[ISet[String]]
      val dependencies = (jv \ "dependencies").extract[ISet[String]]
      val thirdPartyLibraries = (jv \ "thirdPartyLibraries").extract[ISet[String]]
      val layout = DecompileLayout(outputUri, createFolder, srcFolder, libFolder, createSeparateFolderForDexes)
      layout.pkg = pkg
      layout.outputSrcUri = outputSrcUri
      layout.sourceFolders = sourceFolders
      layout.libFolders = libFolders
      layout.dependencies = dependencies
      layout.thirdPartyLibraries = thirdPartyLibraries
      layout
  },
  {
    case layout: DecompileLayout =>
      implicit val formats = format
      val outputUri: FileResourceUri = layout.outputSrcUri
      val createFolder: Boolean = layout.createFolder
      val srcFolder: String = layout.srcFolder
      val libFolder: String = layout.libFolder
      val createSeparateFolderForDexes: Boolean = layout.createSeparateFolderForDexes
      val pkg: String = layout.pkg
      val outputSrcUri: FileResourceUri = layout.outputSrcUri
      val sourceFolders: ISet[String] = layout.sourceFolders
      val libFolders: ISet[String] = layout.libFolders
      val dependencies: ISet[String] = layout.dependencies
      val thirdPartyLibraries: ISet[String] = layout.thirdPartyLibraries
      ("outputUri" -> outputUri) ~
      ("createFolder" -> createFolder) ~
      ("srcFolder" -> srcFolder) ~
      ("libFolder" -> libFolder) ~
      ("createSeparateFolderForDexes" -> createSeparateFolderForDexes) ~
      ("pkg" -> pkg) ~
      ("outputSrcUri" -> outputSrcUri) ~
      ("sourceFolders" -> Extraction.decompose(sourceFolders)) ~
      ("libFolders" -> Extraction.decompose(libFolders)) ~
      ("dependencies" -> Extraction.decompose(dependencies)) ~
      ("thirdPartyLibraries" -> Extraction.decompose(thirdPartyLibraries))
  }
)) 
开发者ID:arguslab,项目名称:Argus-SAF,代码行数:60,代码来源:DecompileLayoutSerializer.scala


示例4: SearchableLanguageValueSerializer

//设置package包名称以及导入依赖的类
package no.ndla.articleapi.model.search

import org.json4s.JsonAST.{JArray, JField, JObject, JString}
import org.json4s.{CustomSerializer, MappingException}
import no.ndla.articleapi.model.domain.Language.UnknownLanguage

class SearchableLanguageValueSerializer extends CustomSerializer[SearchableLanguageValues](format => ( {
  case JObject(items) => SearchableLanguageValues(items.map {
    case JField(name, JString(value)) => LanguageValue(Some(name), value)
  })
}, {
  case x: SearchableLanguageValues =>
    JObject(x.languageValues.map(languageValue => JField(languageValue.lang.getOrElse(UnknownLanguage), JString(languageValue.value))).toList)
}))


class SearchableLanguageListSerializer extends CustomSerializer[SearchableLanguageList](format => ( {
  case JObject(items) => {
    SearchableLanguageList(items.map{
      case JField(name, JArray(fieldItems)) => LanguageValue(Some(name), fieldItems.map{
        case JString(value) => value
        case x => throw new MappingException(s"Cannot convert $x to SearchableLanguageList")
      }.to[Seq])
    })
  }
}, {
  case x: SearchableLanguageList =>
    JObject(x.languageValues.map(languageValue => JField(languageValue.lang.getOrElse(UnknownLanguage), JArray(languageValue.value.map(lv => JString(lv)).toList))).toList)
}))

object SearchableLanguageFormats {
  val JSonFormats = org.json4s.DefaultFormats + new SearchableLanguageValueSerializer + new SearchableLanguageListSerializer
} 
开发者ID:NDLANO,项目名称:article-api,代码行数:34,代码来源:SearchableLanguageFormats.scala


示例5: OptionCellSerializer

//设置package包名称以及导入依赖的类
package com.ntsdev.connect4.wire

import com.ntsdev.connect4.model.Cell
import org.json4s.CustomSerializer
import org.json4s.JsonAST.{JField, JObject, JString}



class OptionCellSerializer extends CustomSerializer[Option[Cell]](format => (
  {
    case JObject(JField("cell", JString(s)) :: Nil) =>
      Cell.fromString(s)
  },
  {
    case x: Option[_] =>
      if(x.isDefined) {
        val value = x.get.toString
        JObject(JField("cell", JString(value)))
      } else {
        JObject(JField("cell", JString("[-]")))
      }

  }
)) 
开发者ID:neilshannon,项目名称:connect4,代码行数:25,代码来源:OptionCellSerializer.scala


示例6: PedestrianIncident

//设置package包名称以及导入依赖的类
package searching

import mapdomain.graph.Coordinate
import org.json4s.CustomSerializer
import org.json4s.JsonAST.JString

case class PedestrianIncident(`type`: IncidentType,
  position: Option[Coordinate] = None,
  from: Option[Coordinate] = None,
  to: Option[Coordinate] = None)

sealed trait IncidentType
case object SidewalkIncidentType extends IncidentType
case object RampIncidentType extends IncidentType
case object StopIncidentType extends IncidentType

object IncidentType {
  val keyMap: Map[String, IncidentType] = Map(
    "sidewalk" -> SidewalkIncidentType,
    "ramp" -> RampIncidentType) withDefaultValue SidewalkIncidentType
}

case object IncidentTypeSerializer extends CustomSerializer[IncidentType](format ? ({
  case JString(s) ? IncidentType.keyMap(s)
}, {
  case incidentType: IncidentType ? JString(IncidentType.keyMap.find(i ? incidentType.equals(i._2)).get._1)
})) 
开发者ID:cspinetta,项目名称:footpath-routing,代码行数:28,代码来源:Incidents.scala


示例7: JSON

//设置package包名称以及导入依赖的类
package se.joham.funrts.util

import org.json4s.{CustomSerializer, Extraction, ShortTypeHints}
import se.joham.funrts.model._
import Extraction.{decompose, extract}
import org.json4s.JsonAST.JValue
import se.gigurra.scalego.serialization.KnownSubTypes
import se.gigurra.scalego.serialization.json.JsonSerializer
import se.joham.funrts.model.FunRtsECS.{ECS, IdTypes}
import org.json4s.jackson.JsonMethods.{compact, parse}
import org.json4s.jackson.JsonMethods.{pretty => prty}


object JSON {

  def writeAst(ecs: ECS): JValue = ecsSerializer.SerializableOps(ecs).toJsonAst
  def    write(ecs: ECS, pretty: Boolean): String = ecsSerializer.SerializableOps(ecs).toJson(pretty)
  def writeAst(terrain: Terrain): JValue = decompose(terrain)
  def    write(terrain: Terrain, pretty: Boolean): String = if (pretty) prty(writeAst(terrain)) else compact(writeAst(terrain))

  def     readEcsAst(ecs: ECS, json: JValue): Unit = ecsSerializer.SerializableOps(ecs).appendJsonAst(json)
  def        readEcs(ecs: ECS, json: String): Unit = ecsSerializer.SerializableOps(ecs).appendJson(json)
  def readTerrainAst(json: JValue): Terrain = extract[Terrain](json)
  def    readTerrain(json: String): Terrain = readTerrainAst(parse(json))


  //////////////////////////////////////////////////////////////////////////////////////

  object TerrainSerializer extends CustomSerializer[Terrain](_ => ({
    case json => extract[TerrainSerializable](json).toTerrain },{
    case terrain: Terrain => decompose(new TerrainSerializable(terrain))
  }))

  case class TerrainSerializable(nx: Int, ny: Int, base64Tiles: String) {
    def this(terrain: Terrain) = this(terrain.nx, terrain.ny, Base64.encodeString(terrain.tiles))
    def toTerrain: Terrain = Terrain(nx, ny, Base64.decodeBinary(base64Tiles))
  }

  implicit lazy val jsonFormats = org.json4s.DefaultFormats + TerrainSerializer + ShortTypeHints(Action.classes)
  val ecsSerializer = new JsonSerializer[IdTypes](
    knownSubtypes = KnownSubTypes.fromShortClassName(types = Action.classes:_*),
    jsonFormats = jsonFormats
  )

} 
开发者ID:GiGurra,项目名称:fun-rts,代码行数:46,代码来源:JSON.scala


示例8: TrainType

//设置package包名称以及导入依赖的类
package models

import org.json4s.CustomSerializer
import org.json4s.JsonDSL._
import scalikejdbc.TypeBinder

sealed abstract class TrainType(val value: Int, val name: String) {
  def toJson = ("value" -> value) ~ ("name" -> name)
}

object TrainType {
  case object Local extends TrainType(1, "??")
  case object Rapid extends TrainType(2, "??")
  case object Express extends TrainType(3, "??")
  case object Shinkansen extends TrainType(4, "???")

  def values = Seq(Local, Rapid, Express, Shinkansen)
  def find(v: Int): Option[TrainType] = values.find(_.value == v)

  implicit def typeBinder: TypeBinder[Int] = TypeBinder.int
  implicit val impl: TypeBinder[TrainType] = TypeBinder(_ getInt _)(_ getInt _).map(find).map(_.getOrElse(Local))
}

object TrainTypeSerializer extends CustomSerializer[TrainType](format => (
  { PartialFunction.empty },
  {
    case x: TrainType =>
      ("value" -> x.value) ~ ("name" -> x.name)
  }
)) 
开发者ID:ponkotuy,项目名称:train-stamp-rally,代码行数:31,代码来源:TrainType.scala


示例9: StationRank

//设置package包名称以及导入依赖的类
package models

import org.json4s.CustomSerializer
import org.json4s.JsonDSL._
import scalikejdbc.TypeBinder

sealed abstract class StationRank(val value: Int, val name: String)

object StationRank {
  case object Top extends StationRank(1, "???") // Tokyo, Nagoya, Osaka
  case object Major extends StationRank(2, "???") // Shinjuku, Nagano, Sapporo etc...
  case object Large extends StationRank(3, "???") // Transfer stations
  case object Middle extends StationRank(4, "???") // Rapid stops
  case object Local extends StationRank(5, "???") // others

  val values = Seq(Top, Major, Large, Middle, Local)
  def find(v: Int): Option[StationRank] = values.find(_.value == v)

  implicit def typeBinder: TypeBinder[Int] = TypeBinder.int
  implicit val impl: TypeBinder[StationRank] = TypeBinder(_ getInt _)(_ getInt _).map { i => find(i).getOrElse(Local) }
}

object StationRankSerializer extends CustomSerializer[StationRank](format => (
  { PartialFunction.empty },
  {
    case x: StationRank =>
      ("value" -> x.value) ~ ("name" -> x.name)
  }
)) 
开发者ID:ponkotuy,项目名称:train-stamp-rally,代码行数:30,代码来源:StationRank.scala


示例10: Account

//设置package包名称以及导入依赖的类
package models

import authes.Role
import org.json4s.CustomSerializer
import org.json4s.JsonDSL._
import responses.AccountMinimal
import scalikejdbc._
import skinny.orm.{Alias, SkinnyCRUDMapperWithId}

case class Account(
    id: Long,
    name: String,
    email: String,
    role: Role,
    password: String
) {
  def save()(implicit session: DBSession): Long = Account.save(this)
  def update()(implicit session: DBSession): Long = Account.update(this)
  def minimal = AccountMinimal(id, name)
}

object Account extends SkinnyCRUDMapperWithId[Long, Account] {
  override val defaultAlias: Alias[Account] = createAlias("a")
  override def extract(rs: WrappedResultSet, n: ResultName[Account]): Account = autoConstruct(rs, n)

  override def idToRawValue(id: Long): Any = id
  override def rawValueToId(value: Any): Long = value.toString.toLong

  def save(account: Account)(implicit session: DBSession): Long =
    createWithAttributes(params(account): _*)

  def update(a: Account)(implicit session: DBSession): Int =
    updateById(a.id).withAttributes(params(a): _*)

  def params(a: Account) = Seq(
    'name -> a.name,
    'email -> a.email,
    'role -> a.role.value,
    'password -> a.password
  )
}

object AccountSerializer extends CustomSerializer[Account](format => (
  { PartialFunction.empty },
  {
    case x: Account =>
      ("id" -> x.id) ~ ("name" -> x.name) ~ ("role" -> x.role.value)
  }
)) 
开发者ID:ponkotuy,项目名称:train-stamp-rally,代码行数:50,代码来源:Account.scala


示例11: Error

//设置package包名称以及导入依赖的类
package validator

import org.json4s.CustomSerializer
import org.json4s.JsonDSL._

abstract class Error {
  def message: String
  def url: Option[String]
}

object ErrorSerializer extends CustomSerializer[Error](format => (
  { PartialFunction.empty },
  {
    case x: Error =>
      ("message" -> x.message) ~ ("url" -> x.url)
  }
)) 
开发者ID:ponkotuy,项目名称:train-stamp-rally,代码行数:18,代码来源:Error.scala


示例12: JsonFormats

//设置package包名称以及导入依赖的类
package com.github.mijicd.waes.representations

import com.github.mijicd.waes.domain._
import org.json4s.JsonAST._
import org.json4s.{CustomSerializer, DefaultFormats}
import spray.httpx.Json4sJacksonSupport

object JsonFormats extends Json4sJacksonSupport {
  override implicit def json4sJacksonFormats = DefaultFormats + StatusSerializer

  object StatusSerializer extends CustomSerializer[Status]( format =>
    (
      {
        case JString(status) =>
          status match {
            case "EQUAL" => Equal
            case "DIFFERENT_LENGTHS" => DifferentLength
            case "DIFFERENT_AT" => DifferentAt
          }
      },
      {
        case s: Status => JString(s.status)
      }
    )
  )
} 
开发者ID:mijicd,项目名称:spray-akka-demo,代码行数:27,代码来源:JsonFormats.scala


示例13:

//设置package包名称以及导入依赖的类
package smarthouse.restapi.http.ws

import java.net.URI
import java.time.OffsetDateTime

import akka.cluster.MemberStatus
import org.json4s.CustomSerializer
import org.json4s.JsonAST.JString

trait JsonSerializers {
  val memberStatusSerializer = new CustomSerializer[MemberStatus](format => ( {
    case JString("Exiting") => MemberStatus.Exiting
    case JString("Up") => MemberStatus.Up
    case JString("Joining") => MemberStatus.Joining
    case JString("Leaving") => MemberStatus.Leaving
    case JString("Removed") => MemberStatus.Removed
    case JString("Down") => MemberStatus.Down
  }, {
    case x: MemberStatus =>
      JString(x.toString)
  }
    ))

  val uriSerializer = new CustomSerializer[URI](format => ( {
    case JString(string) => new URI(string)
  }, {
    case x: URI =>
      JString(x.toString)
  }
    ))

  val offsetDateTime = new CustomSerializer[OffsetDateTime](format => ( {
    case JString(string) => OffsetDateTime.parse(string)
  }, {
    case x: OffsetDateTime =>
      JString(x.toLocalDateTime.toString)
  }
    ))
} 
开发者ID:andrewobukhov,项目名称:smart-house,代码行数:40,代码来源:JsonSerializers.scala


示例14: Hit

//设置package包名称以及导入依赖的类
package model

import org.json4s.CustomSerializer
import org.json4s.JsonAST.{JNull, JString}



trait ResultShooting
case object Hit extends ResultShooting
case object Missed extends ResultShooting
case object AlreadyTaken extends ResultShooting
case object Sunk extends ResultShooting
case object AllSunken extends ResultShooting

object ResultShootingSerializer extends CustomSerializer[ResultShooting](format => (
  {
    case JString(resultShooting) =>  resultShooting match {
      case "Hit" => Hit
      case "Missed" => Missed
      case "AlreadyTaken" => AlreadyTaken
      case "Sunk" => Sunk
      case _ => Missed
    }
    case JNull => null
  },
  {
    case resultShooting:ResultShooting => JString(resultShooting.getClass.getSimpleName.replace("$",""))
  })) 
开发者ID:apellizzaro,项目名称:Battlefield,代码行数:29,代码来源:ResultShooting.scala


示例15: EmptySea

//设置package包名称以及导入依赖的类
package model

import org.json4s.CustomSerializer
import org.json4s.JsonAST.{JNull, JString}



sealed trait SeaStatus
case object EmptySea extends SeaStatus
case object MissedShot extends SeaStatus
case object BattleShipSafe extends SeaStatus
case object BattleShipHit extends SeaStatus
case object BattleShipSunk extends SeaStatus

case object SeaStatusSerializer extends CustomSerializer[SeaStatus](format => (
  {
    case JString(seastatus) =>  seastatus match {
      case "EmptySea" => EmptySea
      case "MissedShot" => MissedShot
      case "BattleShipSafe" => BattleShipSafe
      case "BattleShipHit" => BattleShipHit
      case "BattleShipSunk" => BattleShipSunk
      case _ => EmptySea
    }
    case JNull => null
  },
  {
    case seaStatus:SeaStatus => JString(seaStatus.getClass.getSimpleName.replace("$",""))
  })) 
开发者ID:apellizzaro,项目名称:Battlefield,代码行数:30,代码来源:SeaStatus.scala


示例16: GameSettingUp

//设置package包名称以及导入依赖的类
package model

import org.json4s.CustomSerializer
import org.json4s.JsonAST.{JNull, JString}



sealed trait GameStatus
case object GameSettingUp extends GameStatus
case object GameInProgress extends GameStatus
case object GameEnded extends GameStatus


object GameStatusSerializer extends CustomSerializer[GameStatus](format => (
  {
    case JString(gameStatus) =>  gameStatus match {
      case "GameSettingUp" => GameSettingUp
      case "GameInProgress" => GameInProgress
      case "GameEnded" => GameEnded
    }
    case JNull => null
  },
  {
    case gameStatus:GameStatus => JString(gameStatus.getClass.getSimpleName.replace("$",""))
  })) 
开发者ID:apellizzaro,项目名称:Battlefield,代码行数:26,代码来源:GameStatus.scala


示例17: Dropped

//设置package包名称以及导入依赖的类
package com.pagerduty.scheduler.model

import org.json4s.CustomSerializer
import org.json4s.JsonAST.JString


  case object Dropped extends CompletionResult {
    override protected def stringValue = "Dropped"
    override def isComplete: Boolean = true
  }

  def fromString(completionResult: String): Option[CompletionResult] = {
    completionResult.toLowerCase match {
      case "incomplete" => Some(Incomplete)
      case "success" => Some(Success)
      case "failure" => Some(Failure)
      case "dropped" => Some(Dropped)
      case _ => None
    }
  }
}

class CompletionResultSerializer
    extends CustomSerializer[CompletionResult](
      format =>
        ({
          case JString(s) => CompletionResult.fromString(s).getOrElse(CompletionResult.Failure)
        }, {
          case cr: CompletionResult => JString(cr.toString)
        })
    ) 
开发者ID:PagerDuty,项目名称:scheduler,代码行数:32,代码来源:CompletionResult.scala


示例18: JsonSerializers

//设置package包名称以及导入依赖的类
package io.iohk.ethereum.jsonrpc

import akka.util.ByteString
import io.iohk.ethereum.domain.Address
import org.json4s.JsonAST.{JNull, JString}
import org.json4s.CustomSerializer
import org.spongycastle.util.encoders.Hex

object JsonSerializers {

  object UnformattedDataJsonSerializer extends CustomSerializer[ByteString](_ =>
    (
      { PartialFunction.empty },
      { case bs: ByteString => JString(s"0x${Hex.toHexString(bs.toArray)}") }
    )
  )

  object QuantitiesSerializer extends CustomSerializer[BigInt](_ =>
    (
      {PartialFunction.empty},
      {
        case n: BigInt =>
          if(n == 0)
            JString("0x0")
          else
            JString(s"0x${Hex.toHexString(n.toByteArray).dropWhile(_ == '0')}")
      }
    )
  )

  object OptionNoneToJNullSerializer extends CustomSerializer[Option[_]](formats =>
    (
      {PartialFunction.empty},
      { case None => JNull }
    )
  )

  object AddressJsonSerializer extends CustomSerializer[Address](_ =>
    (
      { PartialFunction.empty },
      { case addr: Address => JString(s"0x${Hex.toHexString(addr.bytes.toArray)}")  }
    )
  )

} 
开发者ID:input-output-hk,项目名称:etc-client,代码行数:46,代码来源:JsonSerializers.scala


示例19: CustomSerializers

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

import java.sql.Timestamp

import org.json4s.CustomSerializer
import org.json4s.JsonAST.{JInt, JNull}

object CustomSerializers {
  val all = List(CustomTimestampSerializer)
}

case object CustomTimestampSerializer extends CustomSerializer1653282364(format =>
  ({
    case JInt(x) => new Timestamp(x.longValue * 1000)
    case JNull => null
  },
    {
      case date: Timestamp => JInt(date.getTime / 1000)
    })) 
开发者ID:miguel-isasmendi,项目名称:example-scala-akka,代码行数:20,代码来源:CustomerSerializers.scala


示例20: TimestampSerializer

//设置package包名称以及导入依赖的类
package articlestreamer.shared.marshalling

import java.sql.Timestamp

import articlestreamer.shared.exception.exceptions._
import com.typesafe.scalalogging.LazyLogging
import org.json4s.JsonAST.{JInt, JLong}
import org.json4s.{CustomSerializer, NoTypeHints, native}

trait CustomJsonFormats extends LazyLogging {

  val dformat: String = "yyyy-MM-dd hh:mm:ss"

  case object TimestampSerializer extends CustomSerializer[java.sql.Timestamp](format => (
    {
      case JInt(l) =>
        try {
          new Timestamp(l.toLong)
        } catch {
          case ex: Throwable => {
            logger.error(s"Error while parsing date : ${ex.getStackTraceAsString}")
            null
          }
        }
      case JLong(l) =>
        try {
          new Timestamp(l)
        } catch {
          case ex: Throwable => {
            logger.error(s"Error while parsing date : ${ex.getStackTraceAsString}")
            null
          }
        }
      case _ => null
    },
    {
      case ts: Timestamp =>
        JLong(ts.getTime)
    }
    )
  )

  implicit val json4sFormats =  native.Serialization.formats(NoTypeHints) + TimestampSerializer

} 
开发者ID:firens,项目名称:article-streamer,代码行数:46,代码来源:CustomJsonFormats.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala CommonFilters类代码示例发布时间:2022-05-23
下一篇:
Scala OrcOutputFormat类代码示例发布时间: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