com.fasterxml.jackson.databind.SerializerProvider Scala Examples

The following examples show how to use com.fasterxml.jackson.databind.SerializerProvider. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: SmileJson4sScalaModule.scala    From spark-druid-olap   with Apache License 2.0 5 votes vote down vote up
package org.json4s.jackson.sparklinedata

import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.databind.Module.SetupContext
import com.fasterxml.jackson.databind.{BeanDescription, JavaType, SerializationConfig}
import com.fasterxml.jackson.databind.SerializerProvider
import com.fasterxml.jackson.databind.ser.Serializers
import org.json4s.jackson.{JValueDeserializerResolver, Json4sScalaModule}
import org.json4s._



class SmileJson4sScalaModule extends Json4sScalaModule {

  override def setupModule(ctxt: SetupContext) {
    ctxt.addSerializers(JValueSerializerResolver)
    ctxt.addDeserializers(JValueDeserializerResolver)
  }
}

object SmileJson4sScalaModule extends SmileJson4sScalaModule {

}

private object JValueSerializerResolver 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 JValueSerializer
  }

}

class JValueSerializer extends
 org.json4s.jackson.JValueSerializer {
  import JValueSerializer.isInt

  override def serialize(value: JValue, json: JsonGenerator, provider: SerializerProvider) {
    value match {
      case JInt(v) if isInt(v) => json.writeNumber(v.intValue)
      case _ => super.serialize(value, json, provider)
    }
  }
}

object JValueSerializer {
  val intMax : BigInt = Int.MaxValue
  val intMin : BigInt = Int.MinValue

  def isInt(i : BigInt) : Boolean =
    i != null && !( i.compare(intMax) > 0 || i.compare(intMin) < 0)

} 
Example 2
Source File: CirceJsonSerializer.scala    From circe-jackson   with Apache License 2.0 5 votes vote down vote up
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)
        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.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()
  }
} 
Example 3
Source File: CustomJson.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.http

import java.io.IOException

import akka.http.scaladsl.model.{MediaRange, MediaType}
import akka.http.scaladsl.model.MediaTypes.`application/json`
import com.fasterxml.jackson.core.io.SegmentedStringWriter
import com.fasterxml.jackson.core.util.BufferRecyclers
import com.fasterxml.jackson.core.{JsonGenerator, JsonProcessingException}
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.databind.{JsonMappingException, JsonSerializer, ObjectMapper, SerializerProvider}
import play.api.libs.json._

object NumberAsStringSerializer extends JsonSerializer[JsValue] {
  private val fieldNamesToTranslate = Set(
    "amount",
    "available",
    "balance",
    "buyMatcherFee",
    "currentReward",
    "desiredReward",
    "effective",
    "fee",
    "feeAmount",
    "generating",
    "in",
    "matcherFee",
    "minIncrement",
    "minSponsoredAssetFee",
    "out",
    "price",
    "quantity",
    "regular",
    "reward",
    "sellMatcherFee",
    "sponsorBalance",
    "totalAmount",
    "totalFee",
    "totalWavesAmount",
    "value"
  )

  override def serialize(value: JsValue, json: JsonGenerator, provider: SerializerProvider): Unit = {
    value match {
      case JsNumber(v)  => json.writeNumber(v.bigDecimal)
      case JsString(v)  => json.writeString(v)
      case JsBoolean(v) => json.writeBoolean(v)

      case JsArray(elements) =>
        json.writeStartArray()
        elements.foreach { t =>
          serialize(t, json, provider)
        }
        json.writeEndArray()

      case JsObject(values) =>
        json.writeStartObject()
        values.foreach {
          case (name, JsNumber(v)) if fieldNamesToTranslate(name) =>
            json.writeStringField(name, v.bigDecimal.toPlainString)
          case (name, jsv) =>
            json.writeFieldName(name)
            serialize(jsv, json, provider)
        }
        json.writeEndObject()

      case JsNull => json.writeNull()
    }
  }
}

object CustomJson {
  val jsonWithNumbersAsStrings: MediaType.WithFixedCharset = `application/json`.withParams(Map("large-significand-format" -> "string"))

  def acceptsNumbersAsStrings(mr: MediaRange): Boolean = mr match {
    case MediaRange.One(`jsonWithNumbersAsStrings`, _) => true
    case _                                             => false
  }

  private lazy val mapper = (new ObjectMapper)
    .registerModule(new SimpleModule("WavesJson").addSerializer(classOf[JsValue], NumberAsStringSerializer))
    .configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, true)

  def writeValueAsString(value: JsValue): String = {
    val sw = new SegmentedStringWriter(BufferRecyclers.getBufferRecycler)
    try mapper.writeValue(sw, value)
    catch {
      case e: JsonProcessingException =>
        throw e
      case e: IOException =>
        // shouldn't really happen, but is declared as possibility so:
        throw JsonMappingException.fromUnexpectedIOE(e)
    }
    sw.getAndClear
  }
} 
Example 4
Source File: Program.scala    From fusion-data   with Apache License 2.0 5 votes vote down vote up
package mass.model.job

import com.fasterxml.jackson.annotation.JsonValue
import com.fasterxml.jackson.core.{ JsonGenerator, JsonParser }
import com.fasterxml.jackson.databind.{ DeserializationContext, SerializerProvider }
import com.fasterxml.jackson.databind.annotation.{ JsonDeserialize, JsonSerialize }
import com.fasterxml.jackson.databind.deser.std.StdDeserializer
import com.fasterxml.jackson.databind.ser.std.StdSerializer
import helloscala.common.data.StringValueName

@JsonSerialize(using = classOf[Program.EnumSer])
@JsonDeserialize(using = classOf[Program.EnumDeser])
sealed abstract class Program(@JsonValue val value: String, val name: String) {
  def toValueName: StringValueName = StringValueName(value, name)
}

object Program {
  case object SCALA extends Program("scala", "Scala")
  case object JAVA extends Program("java", "Java")
  case object PYTHON extends Program("python", "Python")
  case object SH extends Program("sh", "SH")
  case object SQL extends Program("sql", "SQL")
  case object JS extends Program("js", "Javascript")

  val values = Vector(SCALA, JAVA, PYTHON, SH, SQL, JS)

  def fromValue(value: String): Program =
    optionFromValue(value).getOrElse(
      throw new NoSuchElementException(s"Program.values by name not found, it is $value."))

  def optionFromValue(value: String): Option[Program] = {
    val v = value.toLowerCase()
    values.find(_.value == v)
  }

  def fromName(name: String): Program =
    optionFromName(name).getOrElse(throw new NoSuchElementException(s"Program.values by name not found, it is $name."))

  def optionFromName(name: String): Option[Program] = {
    val n = name.toLowerCase()
    values.find(_.name == n)
  }

  class EnumSer extends StdSerializer[Program](classOf[Program]) {
    override def serialize(value: Program, gen: JsonGenerator, provider: SerializerProvider): Unit =
      gen.writeString(value.value)
  }
  class EnumDeser extends StdDeserializer[Program](classOf[Program]) {
    override def deserialize(p: JsonParser, ctxt: DeserializationContext): Program =
      Program.fromValue(p.getValueAsString)
  }
} 
Example 5
Source File: TriggerType.scala    From fusion-data   with Apache License 2.0 5 votes vote down vote up
package mass.model.job

import com.fasterxml.jackson.core.{ JsonGenerator, JsonParser }
import com.fasterxml.jackson.databind.annotation.{ JsonDeserialize, JsonSerialize }
import com.fasterxml.jackson.databind.deser.std.StdDeserializer
import com.fasterxml.jackson.databind.ser.std.StdSerializer
import com.fasterxml.jackson.databind.{ DeserializationContext, SerializerProvider }
import helloscala.common.util.{ IEnumTrait, IEnumTraitCompanion }

@JsonSerialize(using = classOf[TriggerType.EnumSer])
@JsonDeserialize(using = classOf[TriggerType.EnumDeser])
sealed abstract class TriggerType extends IEnumTrait[String] {
  override val value: String = name
}

object TriggerType extends IEnumTraitCompanion[String] {
  self =>
  override type Value = TriggerType

  case object SIMPLE extends TriggerType
  case object CRON extends TriggerType
  case object EVENT extends TriggerType

  override val values = Vector(CRON, EVENT, SIMPLE)

  override def optionFromValue(value: String): Option[TriggerType] = super.optionFromValue(value.toUpperCase())

  class EnumSer extends StdSerializer[TriggerType](classOf[TriggerType]) {
    override def serialize(value: TriggerType, gen: JsonGenerator, provider: SerializerProvider): Unit =
      gen.writeString(value.value)
  }
  class EnumDeser extends StdDeserializer[TriggerType](classOf[TriggerType]) {
    override def deserialize(p: JsonParser, ctxt: DeserializationContext): TriggerType =
      TriggerType.fromValue(p.getValueAsString.toUpperCase())
  }
} 
Example 6
Source File: JsonLifter.scala    From diffy   with GNU Affero General Public License v3.0 5 votes vote down vote up
package ai.diffy.lifter

import com.fasterxml.jackson.core.{JsonGenerator, JsonToken}
import com.fasterxml.jackson.databind.annotation.JsonSerialize
import com.fasterxml.jackson.databind.ser.std.StdSerializer
import com.fasterxml.jackson.databind.{JsonNode, ObjectMapper, SerializerProvider}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import com.twitter.util.Try

import scala.collection.JavaConversions._
import scala.language.postfixOps
import scala.reflect.runtime.universe.runtimeMirror
import scala.tools.reflect.ToolBox
import scala.util.control.NoStackTrace

object JsonLifter {
  @JsonSerialize(using = classOf[JsonNullSerializer])
  object JsonNull
  object JsonParseError extends Exception with NoStackTrace

  val toolbox = runtimeMirror(getClass.getClassLoader).mkToolBox()

  val Mapper = new ObjectMapper with ScalaObjectMapper
  Mapper.registerModule(DefaultScalaModule)
  def apply(obj: Any): JsonNode = Mapper.valueToTree(obj)

  def lift(node: JsonNode): Any = node.asToken match {
    case JsonToken.START_ARRAY        =>
      node.elements.toSeq.map {
        element => lift(element)
      }
    case JsonToken.START_OBJECT       => {
      val fields = node.fieldNames.toSet
      if (fields.exists{ field => Try(toolbox.parse(s"object ${field}123")).isThrow}) {
        node.fields map {field => (field.getKey -> lift(field.getValue))} toMap
      } else {
        FieldMap(
          node.fields map {field => (field.getKey -> lift(field.getValue))} toMap
        )
      }
    }
    case JsonToken.VALUE_FALSE        => false
    case JsonToken.VALUE_NULL         => JsonNull
    case JsonToken.VALUE_NUMBER_FLOAT => node.asDouble
    case JsonToken.VALUE_NUMBER_INT   => node.asLong
    case JsonToken.VALUE_TRUE         => true
    case JsonToken.VALUE_STRING       => node.textValue
    case _                            => throw JsonParseError
  }

  def decode(json: String): JsonNode = Mapper.readTree(json)
  def encode(item: Any): String = Mapper.writer.writeValueAsString(item)
}

class JsonNullSerializer(clazz: Class[Any]) extends StdSerializer[Any](clazz) {
  def this() {
    this(null)
  }

  override def serialize(t: Any, jsonGenerator: JsonGenerator, serializerProvider: SerializerProvider): Unit = {
    jsonGenerator.writeNull()
  }
} 
Example 7
Source File: SqlStatementSerialization.scala    From NSDb   with Apache License 2.0 5 votes vote down vote up
package io.radicalbit.nsdb.common.statement

import com.fasterxml.jackson.core.{JsonGenerator, JsonParser}
import com.fasterxml.jackson.databind.{DeserializationContext, SerializerProvider}
import com.fasterxml.jackson.databind.deser.std.StdDeserializer
import com.fasterxml.jackson.databind.ser.std.StdSerializer

object SqlStatementSerialization {

  object ComparisonOperatorSerialization {

    class ComparisonOperatorJsonSerializer extends StdSerializer[ComparisonOperator](classOf[ComparisonOperator]) {

      override def serialize(value: ComparisonOperator, gen: JsonGenerator, provider: SerializerProvider): Unit =
        gen.writeString(value.toString)
    }

    class ComparisonOperatorJsonDeserializer extends StdDeserializer[ComparisonOperator](classOf[ComparisonOperator]) {

      override def deserialize(p: JsonParser, ctxt: DeserializationContext): ComparisonOperator = {
        p.getText match {
          case "GreaterThanOperator"      => GreaterThanOperator
          case "GreaterOrEqualToOperator" => GreaterOrEqualToOperator
          case "LessThanOperator"         => LessThanOperator
          case "LessOrEqualToOperator"    => LessOrEqualToOperator
        }
      }
    }

  }

  object AggregationSerialization {

    class AggregationJsonSerializer extends StdSerializer[Aggregation](classOf[Aggregation]) {

      override def serialize(value: Aggregation, gen: JsonGenerator, provider: SerializerProvider): Unit =
        gen.writeString(value.toString)
    }

    class AggregationJsonDeserializer extends StdDeserializer[Aggregation](classOf[Aggregation]) {

      override def deserialize(p: JsonParser, ctxt: DeserializationContext): Aggregation = {
        p.getText match {
          case "CountAggregation" => CountAggregation
          case "MaxAggregation"   => MaxAggregation
          case "MinAggregation"   => MinAggregation
          case "SumAggregation"   => SumAggregation
          case "FirstAggregation" => FirstAggregation
          case "LastAggregation"  => LastAggregation
          case "AvgAggregation"   => AvgAggregation
        }
      }
    }

  }

  object LogicalOperatorSerialization {

    class LogicalOperatorJsonSerializer extends StdSerializer[LogicalOperator](classOf[LogicalOperator]) {

      override def serialize(value: LogicalOperator, gen: JsonGenerator, provider: SerializerProvider): Unit =
        gen.writeString(value.toString)
    }

    class LogicalOperatorJsonDeserializer extends StdDeserializer[LogicalOperator](classOf[LogicalOperator]) {

      override def deserialize(p: JsonParser, ctxt: DeserializationContext): LogicalOperator = {
        p.getText match {
          case "NotOperator" => NotOperator
          case "AndOperator" => AndOperator
          case "OrOperator"  => OrOperator
        }
      }
    }

  }
} 
Example 8
Source File: FieldClassType.scala    From NSDb   with Apache License 2.0 5 votes vote down vote up
package io.radicalbit.nsdb.common.protocol

import com.fasterxml.jackson.core.{JsonGenerator, JsonParser}
import com.fasterxml.jackson.databind.annotation.{JsonDeserialize, JsonSerialize}
import com.fasterxml.jackson.databind.{DeserializationContext, SerializerProvider}
import com.fasterxml.jackson.databind.deser.std.StdDeserializer
import com.fasterxml.jackson.databind.ser.std.StdSerializer



@JsonSerialize(using = classOf[FieldClassTypeJsonSerializer])
@JsonDeserialize(using = classOf[FieldClassTypeJsonDeserializer])
sealed trait FieldClassType

case object TimestampFieldType extends FieldClassType
case object ValueFieldType     extends FieldClassType
case object DimensionFieldType extends FieldClassType
case object TagFieldType       extends FieldClassType

class FieldClassTypeJsonSerializer extends StdSerializer[FieldClassType](classOf[FieldClassType]) {

  override def serialize(value: FieldClassType, gen: JsonGenerator, provider: SerializerProvider): Unit =
    gen.writeString(value.toString)

}

class FieldClassTypeJsonDeserializer extends StdDeserializer[FieldClassType](classOf[FieldClassType]) {

  override def deserialize(p: JsonParser, ctxt: DeserializationContext): FieldClassType = {
    p.getText match {
      case "TimestampFieldType" => TimestampFieldType
      case "ValueFieldType"     => ValueFieldType
      case "DimensionFieldType" => DimensionFieldType
      case "TagFieldType"       => TagFieldType
    }
  }
} 
Example 9
Source File: EnumEntrySerializer.scala    From TransmogrifAI   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package com.salesforce.op.utils.json

import com.fasterxml.jackson.core.{JsonGenerator, JsonParser}
import com.fasterxml.jackson.databind.deser.std.StdDeserializer
import com.fasterxml.jackson.databind.ser.std.StdSerializer
import com.fasterxml.jackson.databind.{DeserializationContext, SerializerProvider}
import enumeratum.{Enum, EnumEntry}
import org.json4s.CustomSerializer
import org.json4s.JsonAST.JString

import scala.reflect.ClassTag


  def jackson[A <: EnumEntry: ClassTag](enum: Enum[A]): SerDes[A] = {
    val klazz = implicitly[ClassTag[A]].runtimeClass.asInstanceOf[Class[A]]
    val ser = new StdSerializer[A](klazz) {
      override def serialize(value: A, gen: JsonGenerator, provider: SerializerProvider): Unit = {
        gen.writeString(value.entryName)
      }
    }
    val des = new StdDeserializer[A](klazz) {
      override def deserialize(p: JsonParser, ctxt: DeserializationContext): A = {
        enum.withNameInsensitive(p.getValueAsString)
      }
    }
    new SerDes[A](klazz, ser, des)
  }

} 
Example 10
Source File: CustomJson.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.json

import java.io.IOException

import akka.http.scaladsl.model.MediaType
import akka.http.scaladsl.model.MediaTypes.`application/json`
import com.fasterxml.jackson.core.io.SegmentedStringWriter
import com.fasterxml.jackson.core.util.BufferRecyclers
import com.fasterxml.jackson.core.{JsonGenerator, JsonProcessingException}
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.databind.{JsonMappingException, JsonSerializer, ObjectMapper, SerializerProvider}
import play.api.libs.json._

object NumberAsStringSerializer extends JsonSerializer[JsValue] {

  private val fieldNamesToTranslate = Set(
    "amount",
    "available",
    "balance",
    "buyMatcherFee",
    "currentReward",
    "desiredReward",
    "effective",
    "fee",
    "feeAmount",
    "generating",
    "in",
    "matcherFee",
    "minIncrement",
    "minSponsoredAssetFee",
    "out",
    "price",
    "quantity",
    "regular",
    "reward",
    "sellMatcherFee",
    "sponsorBalance",
    "totalAmount",
    "totalFee",
    "totalWavesAmount",
    "value"
  )

  override def serialize(value: JsValue, json: JsonGenerator, provider: SerializerProvider): Unit = {
    value match {
      case JsNumber(v)  => json.writeNumber(v.bigDecimal)
      case JsString(v)  => json.writeString(v)
      case JsBoolean(v) => json.writeBoolean(v)

      case JsArray(elements) =>
        json.writeStartArray()
        elements.foreach { t =>
          serialize(t, json, provider)
        }
        json.writeEndArray()

      case JsObject(values) =>
        json.writeStartObject()
        values.foreach {
          case (name, JsNumber(v)) if fieldNamesToTranslate(name) =>
            json.writeStringField(name, v.bigDecimal.toPlainString)
          case (name, jsv) =>
            json.writeFieldName(name)
            serialize(jsv, json, provider)
        }
        json.writeEndObject()

      case JsNull => json.writeNull()
    }
  }
}

object CustomJson {

  val jsonWithNumbersAsStrings: MediaType.WithFixedCharset = `application/json`.withParams(Map("large-significand-format" -> "string"))

  private lazy val mapper = (new ObjectMapper)
    .registerModule(new SimpleModule("WavesJson").addSerializer(classOf[JsValue], NumberAsStringSerializer))
    .configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, true)

  def writeValueAsString(value: JsValue): String = {
    val sw = new SegmentedStringWriter(BufferRecyclers.getBufferRecycler)
    try mapper.writeValue(sw, value)
    catch {
      case e: JsonProcessingException =>
        throw e
      case e: IOException =>
        // shouldn't really happen, but is declared as possibility so:
        throw JsonMappingException.fromUnexpectedIOE(e)
    }
    sw.getAndClear
  }
} 
Example 11
Source File: TypedJsonSerializer.scala    From milan   with Apache License 2.0 5 votes vote down vote up
package com.amazon.milan.serialization

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



class TypedJsonSerializer[T <: TypeInfoProvider] extends JsonSerializer[T] {
  override def serialize(value: T,
                         jsonGenerator: JsonGenerator,
                         serializerProvider: SerializerProvider): Unit = {
    val typeName = value.getJsonTypeName

    try {
      jsonGenerator.writeStartObject()
      jsonGenerator.writeStringField("_type", typeName)
      jsonGenerator.writeObject(value)
      jsonGenerator.writeEndObject()
    }
    catch {
      case ex: Throwable => throw new JsonSerializationException(s"Error serializing object of type $typeName.", ex)
    }
  }
}


class JsonSerializationException(message: String, cause: Throwable) extends Exception(message, cause) {

} 
Example 12
Source File: ColumnDateTimeFormats.scala    From milan   with Apache License 2.0 5 votes vote down vote up
package com.amazon.milan.dataformats

import java.time.Instant
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}



class ColumnDateTimeFormatsInstantSerializer(dateTimeFormats: Map[String, DateTimeFormatter]) extends JsonSerializer[Instant] {
  override def serialize(value: Instant,
                         jsonGenerator: JsonGenerator,
                         serializerProvider: SerializerProvider): Unit = {
    val contextName = jsonGenerator.getOutputContext.getCurrentName

    val dateTimeFormatter =
      this.dateTimeFormats.get(contextName) match {
        case Some(formatter) => formatter
        case None => DateTimeFormatter.ISO_INSTANT
      }

    jsonGenerator.writeString(dateTimeFormatter.format(value))
  }
} 
Example 13
Source File: GenericTypedJsonSerializer.scala    From milan   with Apache License 2.0 5 votes vote down vote up
package com.amazon.milan.serialization

import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.databind.{JsonSerializer, SerializerProvider}
import com.typesafe.scalalogging.Logger
import org.slf4j.LoggerFactory



class GenericTypedJsonSerializer[T <: GenericTypeInfoProvider] extends JsonSerializer[T] {
  private val logger = Logger(LoggerFactory.getLogger(getClass))

  override def serialize(value: T,
                         jsonGenerator: JsonGenerator,
                         serializerProvider: SerializerProvider): Unit = {
    val typeName = value.getTypeName
    val genericArgs = value.getGenericArguments
    logger.info(s"Serializing type '$typeName[${genericArgs.map(_.fullName).mkString(", ")}]'.")

    jsonGenerator.writeStartObject()
    jsonGenerator.writeStringField("_type", value.getTypeName)
    jsonGenerator.writeObjectField("_genericArgs", value.getGenericArguments)
    jsonGenerator.writeObject(value)
    jsonGenerator.writeEndObject()
  }
} 
Example 14
Source File: JsonMerkleRootsSerializer.scala    From Sidechains-SDK   with MIT License 5 votes vote down vote up
package com.horizen.serialization

import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.databind
import com.fasterxml.jackson.databind.SerializerProvider
import com.horizen.utils.{ByteArrayWrapper, BytesUtils}

import scala.collection.mutable.Map
import scala.collection.mutable.Iterable

class JsonMerkleRootsSerializer extends databind.JsonSerializer[Option[Map[ByteArrayWrapper, Array[Byte]]]] {

  override def serialize(t: Option[Map[ByteArrayWrapper, Array[Byte]]], jsonGenerator: JsonGenerator, serializerProvider: SerializerProvider): Unit = {
    if(t.isDefined){
      var listOfPair : Iterable[Pair] = t.get.map(k => Pair(BytesUtils.toHexString(k._1.data), BytesUtils.toHexString(k._2)))
      jsonGenerator.writeObject(listOfPair)
    }else{
      jsonGenerator.writeStartArray()
      jsonGenerator.writeEndArray()
    }
  }
}

private case class Pair(key : String, value : String) 
Example 15
Source File: JsonHorizenPublicKeyHashSerializer.scala    From Sidechains-SDK   with MIT License 5 votes vote down vote up
package com.horizen.serialization

import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.databind.{JsonSerializer, SerializerProvider}
import com.horizen.params.TestNetParams
import com.horizen.utils.BytesUtils

// Serialize public key hash bytes as Horizen standard public key address base58 string
class JsonHorizenPublicKeyHashSerializer extends JsonSerializer[Array[Byte]] {
  override def serialize(publicKeyHash: Array[Byte], jsonGenerator: JsonGenerator, serializerProvider: SerializerProvider): Unit = {
    jsonGenerator.writeString(BytesUtils.toHorizenPublicKeyAddress(publicKeyHash, JsonHorizenPublicKeyHashSerializer.testNetParams))
  }
}

object JsonHorizenPublicKeyHashSerializer {
  // TODO: fix this: we should serialize Horizen public key hash depend on Network type
  // In MainNet we will display Horizen public key address wrongly!
  // Unfortunately we have no easy way to access Network params from here.
  private val testNetParams = TestNetParams()
} 
Example 16
Source File: JsonMerklePathSerializer.scala    From Sidechains-SDK   with MIT License 5 votes vote down vote up
package com.horizen.serialization

import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.databind
import com.fasterxml.jackson.databind.SerializerProvider
import com.horizen.utils.{BytesUtils, MerklePath}

import scala.collection.JavaConverters._

class JsonMerklePathSerializer extends databind.JsonSerializer[MerklePath] {

  override def serialize(t: MerklePath, jsonGenerator: JsonGenerator, serializerProvider: SerializerProvider): Unit = {
    var listOfPair : Iterable[Pair] = t.merklePathList.asScala.map(k => Pair(k.getKey.toString, BytesUtils.toHexString(k.getValue)))
    jsonGenerator.writeObject(listOfPair)
  }
}
class JsonMerklePathOptionSerializer extends databind.JsonSerializer[Option[MerklePath]] {

  override def serialize(t: Option[MerklePath], jsonGenerator: JsonGenerator, serializerProvider: SerializerProvider): Unit = {
    if(t.isDefined){
      new JsonMerklePathSerializer().serialize(t.get, jsonGenerator, serializerProvider)
    }else{
      jsonGenerator.writeStartArray()
      jsonGenerator.writeEndArray()
    }
  }
} 
Example 17
Source File: JacksonScalaProvider.scala    From daf-semantics   with Apache License 2.0 5 votes vote down vote up
package it.almawave.kb.http.providers

import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider
import com.fasterxml.jackson.databind.ObjectMapper
import javax.ws.rs.ext.Provider
import javax.ws.rs.Produces
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import javax.ws.rs.core.MediaType
import com.fasterxml.jackson.annotation.JsonInclude

import com.fasterxml.jackson.annotation.JsonAnyGetter

import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.databind.DeserializationFeature
import javax.ws.rs.ext.ContextResolver
import com.fasterxml.jackson.databind.JsonSerializer
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.databind.SerializerProvider
import java.lang.Double
import java.lang.Boolean

@Provider
@Produces(Array(MediaType.APPLICATION_JSON))
class JacksonScalaProvider extends JacksonJaxbJsonProvider with ContextResolver[ObjectMapper] {

  println("\n\nregistered " + this.getClass)

  val mapper = new ObjectMapper()

  mapper
    .registerModule(DefaultScalaModule)
    .setSerializationInclusion(JsonInclude.Include.ALWAYS)

    .configure(SerializationFeature.INDENT_OUTPUT, true)
    .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true)

    .configure(SerializationFeature.WRITE_NULL_MAP_VALUES, true)
    .configure(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED, true)
    .configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, true)

    .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
    .configure(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT, true)
    .configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true)
    .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
    //    .setVisibility(JsonMethod.FIELD, Visibility.ANY);

    .getSerializerProvider.setNullValueSerializer(new JsonSerializer[Object] {
      def serialize(obj: Object, gen: JsonGenerator, provider: SerializerProvider) {
        obj match {
          case bool: Boolean   => gen.writeBoolean(false)
          case number: Integer => gen.writeNumber(0)
          case number: Double  => gen.writeNumber(0.0D)
          case text: String    => gen.writeString("")
          case _               => gen.writeString("")
        }
      }
    })

  super.setMapper(mapper)

  override def getContext(klasses: Class[_]): ObjectMapper = mapper

} 
Example 18
Source File: HttpOrderBook.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.entities

import com.fasterxml.jackson.core.{JsonGenerator, JsonParser}
import com.fasterxml.jackson.databind.annotation.JsonSerialize
import com.fasterxml.jackson.databind.deser.std.StdDeserializer
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.databind.ser.std.StdSerializer
import com.fasterxml.jackson.databind.{DeserializationContext, JsonNode, ObjectMapper, SerializerProvider}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import com.wavesplatform.dex.domain.asset.Asset.{IssuedAsset, Waves}
import com.wavesplatform.dex.domain.asset.{Asset, AssetPair}
import com.wavesplatform.dex.domain.bytes.ByteStr
import com.wavesplatform.dex.domain.model.Denormalization
import com.wavesplatform.dex.model.LevelAgg

@JsonSerialize(using = classOf[HttpOrderBook.Serializer])
case class HttpOrderBook(timestamp: Long, pair: AssetPair, bids: Seq[LevelAgg], asks: Seq[LevelAgg], assetPairDecimals: Option[(Int, Int)] = None)

object HttpOrderBook {

  private val coreTypeSerializers = new SimpleModule()
  coreTypeSerializers.addDeserializer(classOf[AssetPair], new AssetPairDeserializer)

  private val mapper = new ObjectMapper() with ScalaObjectMapper
  mapper.registerModule(DefaultScalaModule)
  mapper.registerModule(coreTypeSerializers)

  private def serialize(value: Any): String = mapper.writeValueAsString(value)

  private class AssetPairDeserializer extends StdDeserializer[AssetPair](classOf[AssetPair]) {

    override def deserialize(p: JsonParser, ctxt: DeserializationContext): AssetPair = {
      val node = p.getCodec.readTree[JsonNode](p)

      def readAssetId(fieldName: String): Asset = {
        val x = node.get(fieldName).asText(Asset.WavesName)
        if (x == Asset.WavesName) Waves else IssuedAsset(ByteStr.decodeBase58(x).get)
      }

      AssetPair(readAssetId("amountAsset"), readAssetId("priceAsset"))
    }
  }

  private def formatValue(value: BigDecimal, decimals: Int): String = new java.text.DecimalFormat(s"0.${"0" * decimals}").format(value)

  private def denormalizeAndSerializeSide(side: Seq[LevelAgg], amountAssetDecimals: Int, priceAssetDecimals: Int, jg: JsonGenerator): Unit = {
    side.foreach { levelAgg =>
      val denormalizedPrice  = Denormalization.denormalizePrice(levelAgg.price, amountAssetDecimals, priceAssetDecimals)
      val denormalizedAmount = Denormalization.denormalizeAmountAndFee(levelAgg.amount, amountAssetDecimals)

      jg.writeStartArray(2)
      jg.writeString(formatValue(denormalizedPrice, priceAssetDecimals))
      jg.writeString(formatValue(denormalizedAmount, amountAssetDecimals))
      jg.writeEndArray()
    }
  }

  def toJson(x: HttpOrderBook): String = serialize(x)

  class Serializer extends StdSerializer[HttpOrderBook](classOf[HttpOrderBook]) {
    override def serialize(x: HttpOrderBook, j: JsonGenerator, serializerProvider: SerializerProvider): Unit = {
      j.writeStartObject()
      j.writeNumberField("timestamp", x.timestamp)

      x.assetPairDecimals.fold {

        j.writeFieldName("pair")
        j.writeStartObject()
        j.writeStringField("amountAsset", x.pair.amountAssetStr)
        j.writeStringField("priceAsset", x.pair.priceAssetStr)
        j.writeEndObject()

        j.writeArrayFieldStart("bids")
        x.bids.foreach(j.writeObject)
        j.writeEndArray()

        j.writeArrayFieldStart("asks")
        x.asks.foreach(j.writeObject)
        j.writeEndArray()

      } {
        case (amountAssetDecimals, priceAssetDecimals) =>
          j.writeArrayFieldStart("bids")
          denormalizeAndSerializeSide(x.bids, amountAssetDecimals, priceAssetDecimals, j)
          j.writeEndArray()

          j.writeArrayFieldStart("asks")
          denormalizeAndSerializeSide(x.asks, amountAssetDecimals, priceAssetDecimals, j)
          j.writeEndArray()
      }

      j.writeEndObject()
    }
  }
}