org.json4s._ Scala Examples
The following examples show how to use org.json4s._.
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: CustomSubTypesSerializer.scala From reliable-http-client with Apache License 2.0 | 5 votes |
package rhttpc.transport.json4s import org.json4s.reflect.TypeInfo import org.json4s.{Formats, Serializer, _} import scala.reflect.ClassTag class CustomSubTypesSerializer[T: Manifest, JV <: JValue: ClassTag]( ser: Formats => (PartialFunction[JV, T], PartialFunction[T, JV])) extends Serializer[T] { private val Class = implicitly[Manifest[T]].runtimeClass def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), T] = { val d = ser(format)._1 val pf: PartialFunction[(TypeInfo, JValue), T] = { case (TypeInfo(clazz, _), jValue: JV) if Class.isAssignableFrom(clazz) && d.isDefinedAt(jValue) => d(jValue) } pf } def serialize(implicit format: Formats): PartialFunction[Any, JValue] = { val s = ser(format)._2 val pf: PartialFunction[Any, JValue] = { case obj: T if s.isDefinedAt(obj) => s(obj) } pf } }
Example 2
Source File: package.scala From maha with Apache License 2.0 | 5 votes |
// Copyright 2017, Yahoo Holdings Inc. // Licensed under the terms of the Apache License 2.0. Please see LICENSE file in project root for terms. package com.yahoo.maha.service import com.netflix.archaius.config.PollingDynamicConfig import com.yahoo.maha.service.config.dynamic.DynamicConfigurations import com.yahoo.maha.service.config.dynamic.DynamicConfigurationUtils._ import grizzled.slf4j.Logging import org.json4s.{JValue, _} import org.json4s.jackson.JsonMethods.parse import org.json4s.scalaz.JsonScalaz import org.json4s.scalaz.JsonScalaz.{JSONR, _} package object request extends Logging { implicit val formats = org.json4s.DefaultFormats private var dynamicConfigurations:Option[DynamicConfigurations] = None def setDynamicConfigurations(value: DynamicConfigurations): Unit = dynamicConfigurations = Some(value) def fieldExtended[A: JSONR](name: String)(json: JValue): Result[A] = { val dynamicField = (extractDynamicFields(json)).filter(f => f._2._1.equals(name)).headOption val result = { if (dynamicField.isDefined && dynamicConfigurations.isDefined) { val defaultValue = JsonScalaz.fromJSON[A](parse(dynamicField.get._2._2)) dynamicConfigurations.get.addProperty(dynamicField.get._1, defaultValue.toOption.get.asInstanceOf[Int]) val dynamicValue = JsonScalaz.fromJSON[A](parse(dynamicConfigurations.get.getDynamicConfiguration(dynamicField.get._1).get.toString)) if (dynamicValue.isSuccess) { dynamicValue } else { error(s"Failed to fetch dynamic config value failure: $dynamicValue. Returning default: $defaultValue") defaultValue } } else { field[A](name)(json) } } result.leftMap { nel => nel.map { case UnexpectedJSONError(was, expected) => UncategorizedError(name, s"unexpected value : $was expected : ${expected.getSimpleName}", List.empty) case a => a } } } }
Example 3
Source File: JsoneyStringTest.scala From sparta with Apache License 2.0 | 5 votes |
package com.stratio.sparta.sdk.properties import org.json4s.jackson.JsonMethods._ import org.json4s.jackson.Serialization.write import org.json4s.{DefaultFormats, _} import org.junit.runner.RunWith import org.scalatest.junit.JUnitRunner import org.scalatest.{Matchers, WordSpecLike} @RunWith(classOf[JUnitRunner]) class JsoneyStringTest extends WordSpecLike with Matchers { "A JsoneyString" should { "have toString equivalent to its internal string" in { assertResult("foo")(new JsoneyString("foo").toString) } "be deserialized if its JSON" in { implicit val json4sJacksonFormats = DefaultFormats + new JsoneyStringSerializer() val result = parse( """{ "foo": "bar" }""").extract[JsoneyString] assertResult(new JsoneyString( """{"foo":"bar"}"""))(result) } "be deserialized if it's a String" in { implicit val json4sJacksonFormats = DefaultFormats + new JsoneyStringSerializer() val result = parse("\"foo\"").extract[JsoneyString] assertResult(new JsoneyString("foo"))(result) } "be deserialized if it's an Int" in { implicit val json4sJacksonFormats = DefaultFormats + new JsoneyStringSerializer() val result = parse("1").extract[JsoneyString] assertResult(new JsoneyString("1"))(result) } "be serialized as JSON" in { implicit val json4sJacksonFormats = DefaultFormats + new JsoneyStringSerializer() var result = write(new JsoneyString("foo")) assertResult("\"foo\"")(result) result = write(new JsoneyString("{\"foo\":\"bar\"}")) assertResult("\"{\\\"foo\\\":\\\"bar\\\"}\"")(result) } "be deserialized if it's an JBool" in { implicit val json4sJacksonFormats = DefaultFormats + new JsoneyStringSerializer() val result = parse("true").extract[JsoneyString] assertResult(new JsoneyString("true"))(result) } "have toSeq equivalent to its internal string" in { assertResult(Seq("o"))(new JsoneyString("foo").toSeq) } } }
Example 4
Source File: KerasModel.scala From jigg with Apache License 2.0 | 5 votes |
package jigg.ml.keras import breeze.linalg.DenseMatrix import jigg.util.HDF5Object import org.json4s.jackson.JsonMethods._ import org.json4s.{DefaultFormats, _} class KerasModel(model: HDF5Object) { private val kerasAttribute = model.checkAndGetAttribute("keras_version") private val modelAttribute = model.checkAndGetAttribute("model_config") private val weightGroups = model.checkAndGetGroup("model_weights") def parseConfigToSeq(config: String): Seq[Map[String, Any]] = { val jsonValue = parse(config) implicit val formats = DefaultFormats val jsonList = jsonValue.extract[Map[String, Any]] jsonList("config").asInstanceOf[Seq[Map[String, Any]]] } private val modelValues = parseConfigToSeq(modelAttribute.getValue(0).toString) def getConfigs(x: Map[String, Any]): Map[String, Any] = x("config").asInstanceOf[Map[String,Any]] def constructNetwork(values: Seq[Map[String, Any]]): Seq[Functor] = values.map{ x => { val configs = getConfigs(x) val functor = x("class_name").toString match { case "Activation" => configs("activation").toString match{ case "relu" => Relu case "softmax" => Softmax case "sigmoid" => Sigmoid case "tanh" => Tanh } case "Convolution1D" => Convolution1D(configs, weightGroups) case "Dense" => Dense(configs, weightGroups) case "Embedding" => Embedding(configs, weightGroups) case "Flatten" => Flatten case _ => Empty } functor } } private val graph:Seq[Functor] = constructNetwork(modelValues) def convert(input: DenseMatrix[Float]): DenseMatrix[Float] = callFunctors(input, graph) private def callFunctors(input: DenseMatrix[Float], unprocessed:Seq[Functor]): DenseMatrix[Float] = unprocessed match { case functor :: tail => val interOutput = functor.convert(input) callFunctors(interOutput, tail) case Nil => input } }
Example 5
Source File: LookupTable.scala From jigg with Apache License 2.0 | 5 votes |
package jigg.util import java.io.Reader import breeze.linalg.DenseMatrix import org.json4s.{DefaultFormats, _} import org.json4s.jackson.JsonMethods import org.json4s.JsonAST.JValue class LookupTable(rawTable: JValue) { implicit private val formats = DefaultFormats private val tables = rawTable.extract[Map[String, Map[String, Map[String, String]]]] private val key2id = tables("_lookup")("_key2id") private val id2key = tables("_lookup")("_id2key") // For raw text def encodeCharacter(str: String): DenseMatrix[Float] = { val strArray = str.map{x => // Note: For skipping unknown character, this encoder returns dummy id. key2id.getOrElse(x.toString, "3").toFloat }.toArray new DenseMatrix[Float](1, str.length, strArray) } // For list of words def encodeWords(words: Array[String]): DenseMatrix[Float] = { val wordsArray = words.map{x => // Note: For skipping unknown words, this encoder returns dummy id. key2id.getOrElse(x.toString, "3").toFloat } new DenseMatrix[Float](1, words.length, wordsArray) } def decode(data: DenseMatrix[Float]): Array[String] = data.map{x => id2key.getOrElse(x.toInt.toString, "NONE")}.toArray def getId(key: String): Int = key2id.getOrElse(key, "0").toInt def getId(key: Char): Int = getId(key.toString) def getKey(id: Int): String = id2key.getOrElse(id.toString, "UNKNOWN") } object LookupTable { // Load from a path on the file system def fromFile(path: String) = mkTable(IOUtil.openIn(path)) // Load from class loader def fromResource(path: String) = mkTable(IOUtil.openResourceAsReader(path)) private def mkTable(input: Reader) = { val j = try { JsonMethods.parse(input) } finally { input.close } new LookupTable(j) } }
Example 6
Source File: SwaggerSupport.scala From chatoverflow with Eclipse Public License 2.0 | 5 votes |
package org.codeoverflow.chatoverflow.ui.web import org.codeoverflow.chatoverflow.Launcher import org.json4s.JsonDSL._ import org.json4s.{JValue, _} import org.scalatra.ScalatraServlet import org.scalatra.swagger.{Api, ApiInfo, JacksonSwaggerBase, Swagger} override def renderSwagger2(docs: List[Api]): JValue = { val swagger2 = super.renderSwagger2(docs) val schemes: JObject = "schemes" -> List("http") val host: JObject = "host" -> s"localhost:${Launcher.server.get.port}" val additionalElements = schemes ~ host additionalElements merge swagger2 } } object CodeOverflowApiInfo extends ApiInfo( "Code Overflow API", "This API is the main entry point of the Chat Overflow GUI and third party projects.", "http://codeoverflow.org", "[email protected]", "Eclipse Public License 2.0", "https://github.com/codeoverflow-org/chatoverflow/blob/master/LICENSE") class CodeOverflowSwagger(apiVersion: String) extends Swagger(Swagger.SpecVersion, apiVersion, CodeOverflowApiInfo)
Example 7
Source File: ArrayParam.scala From mmlspark with MIT License | 5 votes |
// Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in project root for information. package org.apache.spark.ml.param import org.apache.spark.annotation.DeveloperApi import org.json4s.{DefaultFormats, _} import org.json4s.jackson.JsonMethods.{compact, parse, render} import scala.collection.JavaConverters._ def w(value: java.util.List[_]): ParamPair[Array[_]] = w(value.asScala.toArray) override def jsonEncode(value: Array[_]): String = { import org.json4s.JsonDSL._ value match { case intArr: Array[Int] => compact(render(intArr.toSeq)) case dbArr: Array[Double] => compact(render(dbArr.toSeq)) case strArr: Array[String] => compact(render(strArr.toSeq)) case blArr: Array[Boolean] => compact(render(blArr.toSeq)) case intArr: Array[Integer] => compact(render(intArr.map(_.toLong).toSeq)) case _ => throw new IllegalArgumentException("Internal type not json serializable") } } override def jsonDecode(json: String): Array[_] = { implicit val formats: DefaultFormats.type = DefaultFormats parse(json).extract[Seq[_]].toArray } }
Example 8
Source File: LambdaHTTPApiAnnotation.scala From quaich with Apache License 2.0 | 5 votes |
package codes.bytes.quaich.api.http.macros import scala.annotation.{StaticAnnotation, compileTimeOnly} import scala.language.postfixOps import scala.reflect.macros.blackbox import scala.language.experimental.macros object LambdaHTTPApi { // todo - check for companion object and reject def annotation_impl(c: blackbox.Context)(annottees: c.Expr[Any]*): c.Expr[Any] = { import c.universe._ import Flag._ val p = c.enclosingPosition val inputs = annottees.map(_.tree).toList val result: Tree = inputs match { case (cls @ q"$mods class $name[..$tparams] extends ..$parents { ..$body }") :: Nil if mods.hasFlag(ABSTRACT) ⇒ c.abort(p, "! The @LambdaHTTPApi annotation is not valid on abstract classes.") cls // todo - detect and handle companion object! case (cls @ q"$mods class $name[..$tparams] extends ..$parents { ..$body }") :: Nil ⇒ //val baseName = name.decodedName.toString //val handlerName = TermName(s"$baseName$$RequestHandler") //val handlerName = name.toTermName val handlerName = name.asInstanceOf[TypeName].toTermName val cls = q""" $mods class $name[..$tparams]( val request: codes.bytes.quaich.api.http.LambdaHTTPRequest, val context: codes.bytes.quaich.api.http.LambdaContext ) extends ..$parents with codes.bytes.quaich.api.http.HTTPHandler { import org.json4s.jackson.JsonMethods._ import org.json4s.jackson.Serialization import org.json4s.jackson.Serialization._ import org.json4s.{NoTypeHints, _} protected implicit val formats = Serialization.formats(NoTypeHints) ..$body } """ val obj = q""" object $handlerName extends codes.bytes.quaich.api.http.HTTPApp { def newHandler( request: codes.bytes.quaich.api.http.LambdaHTTPRequest, context: codes.bytes.quaich.api.http.LambdaContext ): codes.bytes.quaich.api.http.HTTPHandler = new $name(request, context) } """ q"$cls; $obj" case Nil ⇒ c.abort(p, s"Cannot annotate an empty Tree.") case _ ⇒ c.abort(p, s"! The @LambdaHTTPApi Annotation is only valid on non-abstract Classes") } //c.info(p, "result: " + result, force = true) c.Expr[Any](result) } } @compileTimeOnly("Setup the macro paradise compiler plugin to enable expansion of macro annotations.") class LambdaHTTPApi extends StaticAnnotation { def macroTransform(annottees: Any*): Any = macro LambdaHTTPApi.annotation_impl } // vim: set ts=2 sw=2 sts=2 et:
Example 9
Source File: Inputs.scala From flamy with Apache License 2.0 | 5 votes |
package com.flaminem.flamy.model import org.json4s.{DefaultFormats, _} import org.json4s.native.JsonMethods._ def readFromString[T: Manifest](jsonData: String, subPath: String*) (implicit formats: Formats = DefaultFormats): T = { val fullAST = parse(jsonData) val jsonAST = subPath.foldLeft(fullAST){case (ast, subField) => ast\subField} jsonAST.extract[T] } def fromJson(json: String): Inputs = { readFromString[Inputs](json) } object NoInputs extends Inputs(Set(), Set()) }