当前位置: 首页>>代码示例>>Scala>>正文


Scala JsonNode类代码示例

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


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

示例1: Truck

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

import scala.collection.JavaConverters._
import com.fasterxml.jackson.databind.{ ObjectMapper, JsonNode }
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import play.api.Play
import sys.process._

case class Truck (
  name: String,
  address: String,
  cuisine: List[String],
  url: String) {
  override def toString: String = s"""$name (${cuisine.mkString(",")}) @ $address [$url]"""
}

object Truck {
  def newObjectMapper: ObjectMapper = {
    val m = new ObjectMapper()
    m.registerModule(DefaultScalaModule)
  }

  private[Truck] lazy val mapper = newObjectMapper

  val defaultLat = Play.maybeApplication.flatMap(_.configuration.getDouble("foodtrucks.latitude")).getOrElse(0.0)
  val defaultLon = Play.maybeApplication.flatMap(_.configuration.getDouble("foodtrucks.longitude")).getOrElse(0.0)

  def apply(jsonNode: JsonNode): Truck = {
    val info = jsonNode.get("obj")

    Truck(
      info.get("name").asText,
      info.get("last_seen").get("address").asText,
      info.get("cuisine").elements.asScala.map(_.asText).toList,
      info.get("url").asText
    )
  }

  def listAll(lat: Double = defaultLat, lon: Double = defaultLon): List[Truck] = {
    val result = Seq("curl", "-XGET", s"http://nyctruckfood.com/api/trucks/search?q=$lat,$lon").!!
    mapper.readTree(result).elements.asScala.map(Truck(_)).toList
  }
} 
开发者ID:andy327,项目名称:slack-foodtrucks,代码行数:44,代码来源:Truck.scala

示例2: JsonValidationResult

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

import com.fasterxml.jackson.databind.JsonNode
import com.github.fge.jsonschema.main.{JsonSchema, JsonSchemaFactory}
import services.json.MarshallableImplicits._

import scala.collection.JavaConversions._


object JsonValidationResult {
  def apply(success: Boolean, errors: Iterable[JsonNode]) = if(success) ValidJson else InvalidJson(errors)
}

sealed trait JsonValidationResult

case object ValidJson extends JsonValidationResult
case class InvalidJson(errors: Iterable[JsonNode]) extends JsonValidationResult

object JsonValidator {
  val schemaFactory = JsonSchemaFactory.byDefault()

  def validateJson(schemaAsString: String, jsonString: String): JsonValidationResult = {
    val schemaAsJsonNode = schemaAsString.fromJson[JsonNode]
    val jsonSchema = schemaFactory.getJsonSchema(schemaAsJsonNode)
    validateJson(jsonSchema, jsonString)
  }

  def validateJsonFromRemoteSchema(schemaUrl: String, jsonString: String): JsonValidationResult = {
    val jsonSchema = schemaFactory.getJsonSchema(schemaUrl)
    validateJson(jsonSchema, jsonString)
  }

  private def validateJson(jsonSchema: JsonSchema, jsonString: String): JsonValidationResult = {
    val json = jsonString.fromJson[JsonNode]
    val report = jsonSchema.validate(json)
    JsonValidationResult(report.isSuccess, report.map(_.asJson))
  }
} 
开发者ID:jeroenr,项目名称:reactive-mongo-demo,代码行数:39,代码来源:JsonValidator.scala

示例3: FakeService

//设置package包名称以及导入依赖的类
package com.github.ikhoon.app.v1.fake

import javax.inject.{ Inject, Named }

import com.fasterxml.jackson.databind.JsonNode
import com.twitter.finatra.httpclient.{ HttpClient, RequestBuilder }
import com.twitter.util.{ Await, Duration, Future }
import com.typesafe.config.Config

class FakeService @Inject() (@Named("fake") httpClient: HttpClient, config: Config) {
  def withSleepAsync(sec: Int): Future[JsonNode] = {
    val url = s"/api/?sleep=$sec"
    httpClient.executeJson[JsonNode](RequestBuilder.get(url))
  }

  def withSleepSync(sec: Int): JsonNode = {
    val url = s"/api/?sleep=$sec"
    val jsonNode = httpClient.executeJson[JsonNode](RequestBuilder.get(url))
    Await.result(jsonNode, Duration.fromSeconds(100))
  }
} 
开发者ID:ikhoon,项目名称:finatra-mysql-seed,代码行数:22,代码来源:FakeService.scala

示例4: BulkItemResponseDeserializer

//设置package包名称以及导入依赖的类
package com.github.thanhtien522.eshttpclient.entities

import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.{DeserializationContext, JsonDeserializer, JsonNode}


class BulkItemResponseDeserializer extends JsonDeserializer[BulkItemResponse] {

  override def deserialize(p: JsonParser, ctxt: DeserializationContext): BulkItemResponse = {
    val node = p.getCodec.readTree[JsonNode](p)
    node.fieldNames().next() match {
      case "index" => BulkItemResponse("index", p.getCodec.treeToValue(node.get("index"), classOf[IndexResponse]))
      case "create" => BulkItemResponse("create", p.getCodec.treeToValue(node.get("create"), classOf[IndexResponse]))
      case "update" => BulkItemResponse("update", p.getCodec.treeToValue(node.get("update"), classOf[UpdateResponse]))
      case "delete" => BulkItemResponse("delete", p.getCodec.treeToValue(node.get("delete"), classOf[DeleteResponse]))
      case s => throw new Exception("Deserialize BulkItemResponse failure. Unhandled action name `" + s + "`")
    }
  }
}

class ErrorDeserializer extends JsonDeserializer[Error] {
  override def deserialize(p: JsonParser, ctxt: DeserializationContext): Error = {
    val node = p.getCodec.readTree[JsonNode](p)

    if (node.isTextual) {
      Error("exception", node.asText(), null)
    } else if (node.isObject) {
      val `type` = node.get("type").asText()
      val reason = node.get("reason").asText()
      val caused = if (node.has("caused_by")) p.getCodec.treeToValue(node.get("caused_by"), classOf[Error]) else null
      Error(`type`, reason, caused)
    } else {
      throw new Exception(s"Deserialize Error failure. Expected STRING or OBJECT, actual ${node.getNodeType.toString}")
    }
  }
} 
开发者ID:thanhtien522,项目名称:es-http-client,代码行数:37,代码来源:Deserializers.scala

示例5: ELBSSLCertificateLambdaSpec

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

import com.amazonaws.services.lambda.runtime.events.SNSEvent
import com.amazonaws.services.lambda.runtime.events.SNSEvent.{SNS, SNSRecord}
import com.fasterxml.jackson.databind.{DeserializationFeature, JsonNode, ObjectMapper}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import org.scalatest.{FlatSpec, Matchers}

import scala.collection.JavaConversions._
import scala.collection.JavaConverters._
import scala.io.Source



class ELBSSLCertificateLambdaSpec extends FlatSpec with Matchers {
  val mapper = new ObjectMapper() with ScalaObjectMapper
  mapper.registerModule(DefaultScalaModule).configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

  def produceS3Event: JsonNode =
    mapper.readValue(Source.fromInputStream(getClass.getResourceAsStream("/sns_s3_event.json")).getLines.mkString, classOf[JsonNode])

  def toEvent: SNSEvent = {
    val event = new SNSEvent()
    val record = new SNSRecord()
    val sns = new SNS()
    val map = produceS3Event
    sns.setMessage(map.path("Records").get(0).path("Sns").path("Message").asText())
    record.setSns(sns)
    event.setRecords(List[SNSRecord](record))
    event
  }

  "An S3 event" should "run lambda successfully" in {
    val mainObj = new ELBSSLCertificateLambda
    val something = mainObj.configureELBCert(toEvent)
    something.asScala.head shouldBe "Status code for setting arn:aws:iam::my_acct:server-certificate/ocelotconsulting-demo.com ELB certificate for myelb is 200."
  }
} 
开发者ID:ocelotconsulting,项目名称:elb-ssl-cert-lambda,代码行数:40,代码来源:ELBSSLCertificateLambdaSpec.scala

示例6: DplaJsonTraversable

//设置package包名称以及导入依赖的类
package la.dp.sitemap

import java.io.InputStream

import com.fasterxml.jackson.core.JsonToken
import com.fasterxml.jackson.core.JsonToken._
import com.fasterxml.jackson.databind.{JsonNode, ObjectMapper}


class DplaJsonTraversable(inputStream: InputStream) extends Traversable[JsonNode] {

  override def hasDefiniteSize = false

  override def foreach[U](f: (JsonNode) => U): Unit = {

    try {
      val parser = DplaJsonTraversable.jsonFactory.createParser(inputStream)
      assume(parser.nextToken() == JsonToken.START_ARRAY)

      while (parser.nextToken() != END_ARRAY) {
        if (parser.currentToken() == START_OBJECT) {
          val node = parser.readValueAsTree[JsonNode]
          f(node)
        }
      }

    } finally {
      inputStream.close()
    }
  }

  override def toString(): String = "DplaJsonTraversable: " + inputStream.toString
}

object DplaJsonTraversable {
  private val objectMapper = new ObjectMapper()
  private val jsonFactory = objectMapper.getFactory
} 
开发者ID:dpla,项目名称:sitemap,代码行数:39,代码来源:DplaJsonTraversable.scala

示例7: Validator

//设置package包名称以及导入依赖的类
package hmrc.sdil.domain

import java.io.File
import com.github.fge.jsonschema.core.report.ProcessingReport
import com.github.fge.jsonschema.main._
import com.github.fge.jackson.JsonLoader
import com.fasterxml.jackson.databind.JsonNode

package object jsonvalidator {
  implicit class Validator(data: JsonNode) {
    val factory = JsonSchemaFactory.byDefault
    val validator = factory.getValidator

    def validateAgainst(schema: JsonNode): Either[ProcessingReport, JsonNode] = {
      val report = validator.validate(schema, data)
      if (report.isSuccess) {
        Right(data)
      } else {
        Left(report)
      }
    }
  }

  implicit class JsonHelper(val sc: StringContext) {
    def json(args: Any*): JsonNode = JsonLoader.fromString(sc.s(args))
    def jsonFile(args: Any*): JsonNode = JsonLoader.fromFile(new File(sc.parts.mkString(" ")))
  }
} 
开发者ID:hmrc,项目名称:sdil-domain,代码行数:29,代码来源:Validator.scala

示例8: Paging

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

import com.fasterxml.jackson.databind.JsonNode

sealed abstract class Paging[+A] extends Product with Serializable

object Paging {
  def fromIterator[A](it: Iterator[A]): Paging[A] = {
    if (it.hasNext) {
      val next = Lazy(it.next())
      Page(next, Lazy {
        next()
        fromIterator(it)
      })
    } else EOF
  }

  final case class Page[A](data: Lazy[A], next: Lazy[Paging[A]]) extends Paging[A]

  case object EOF extends Paging[Nothing]
}

sealed abstract class PageType extends Product with Serializable

object PageType {
  final case class TablePaging(select: Ast.Select, data: List[JsonNode]) extends PageType
  final case class TableNamePaging(names: Seq[String]) extends PageType
} 
开发者ID:joprice,项目名称:dynamite,代码行数:29,代码来源:Paging.scala

示例9: ConfigFile

//设置package包名称以及导入依赖的类
package moe.pizza.auth.config

import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.databind.JsonNode
import moe.pizza.auth.adapters.GraderChain
import moe.pizza.auth.adapters.PilotGraderLike.PilotGraderFactory
import moe.pizza.auth.interfaces.PilotGrader
import moe.pizza.auth.webapp.oauth.OAuthApplication

import scala.concurrent.ExecutionContext
import org.http4s.client.Client


object ConfigFile {
  case class PingBotConfig(
      host: String,
      password: String
  )
  case class EmbeddedLdapConfig(
      instancePath: String = "./ldap",
      port: Int = 389,
      basedn: String = "ou=pizza",
      host: String = "localhost",
      password: Option[String] = None
  )
  case class AuthGroupConfig(closed: List[String],
                             open: List[String],
                             public: List[String])

  case class AuthConfig(
      domain: String,
      corporation: String,
      alliance: String,
      groupName: String,
      groupShortName: String,
      groups: AuthGroupConfig,
      graders: List[JsonNode],
      pingbot: Option[PingBotConfig],
      restkeys: List[String],
      applications: List[OAuthApplication] = List()
  ) {
    def constructGraders(c: ConfigFile)(
        implicit client: Client): PilotGrader =
      new GraderChain(
        graders.map(g => PilotGraderFactory.fromYaml(g, c)).flatten.toList)

  }
  case class CrestConfig(
      @JsonProperty("login_url") loginUrl: String,
      @JsonProperty("crest_url") crestUrl: String,
      clientID: String,
      secretKey: String,
      redirectUrl: String
  )
  case class ConfigFile(
      crest: CrestConfig,
      auth: AuthConfig,
      embeddedldap: EmbeddedLdapConfig
  )

} 
开发者ID:NoApologies420,项目名称:Alliance-Auth,代码行数:62,代码来源:ConfigFile.scala

示例10: SocketIOSessionFlowHelper

//设置package包名称以及导入依赖的类
package play.socketio.javadsl

import java.util.Optional
import java.util.concurrent.CompletionStage
import java.util.function.{ BiFunction, Function }

import akka.NotUsed
import akka.stream.Materializer
import akka.stream.javadsl.Flow
import com.fasterxml.jackson.databind.JsonNode
import play.api.libs.json.Json
import play.mvc.Http.RequestHeader
import play.socketio.{ SocketIOConfig, SocketIOEvent, SocketIOSession, SocketIOSessionFlow }

import scala.concurrent.ExecutionContext
import scala.Function.unlift
import scala.compat.java8.FutureConverters._
import scala.compat.java8.OptionConverters._


private[javadsl] object SocketIOSessionFlowHelper {

  def createEngineIOSessionHandler[SessionData](
    config:                     SocketIOConfig,
    connectCallback:            BiFunction[RequestHeader, String, CompletionStage[SessionData]],
    errorHandler:               Function[Throwable, Optional[JsonNode]],
    defaultNamespaceCallback:   Function[SocketIOSession[SessionData], Flow[SocketIOEvent, SocketIOEvent, NotUsed]],
    connectToNamespaceCallback: BiFunction[SocketIOSession[SessionData], String, Optional[Flow[SocketIOEvent, SocketIOEvent, NotUsed]]]
  )(implicit ec: ExecutionContext, mat: Materializer) = {
    SocketIOSessionFlow.createEngineIOSessionHandler[SessionData](
      config,
      (request, sid) => connectCallback(request.asJava, sid).toScala,
      unlift(t => errorHandler(t).asScala.map(Json.toJson(_))),
      session => defaultNamespaceCallback(session).asScala,
      unlift {
        case (session, sid) => connectToNamespaceCallback(session, sid).asScala.map(_.asScala)
      }
    )
  }
} 
开发者ID:playframework,项目名称:play-socket.io,代码行数:41,代码来源:SocketIOSessionFlowHelper.scala

示例11: JsonLifter

//设置package包名称以及导入依赖的类
package com.twitter.diffy.lifter

import com.fasterxml.jackson.core.JsonToken
import com.fasterxml.jackson.databind.{JsonNode, ObjectMapper}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import com.twitter.util.{Try, NoStacktrace}

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

object JsonLifter {
  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)
      }  sortBy { _.toString }
    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)
} 
开发者ID:sachinmanchanda,项目名称:diffy_unicast,代码行数:51,代码来源:JsonLifter.scala

示例12: IAMServerCertificateLambdaFromString

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

import com.amazonaws.services.lambda.runtime.events.SNSEvent
import com.amazonaws.services.lambda.runtime.events.SNSEvent.{SNS, SNSRecord}

import scala.collection.JavaConversions._
import com.amazonaws.services.s3.event.S3EventNotification.S3Entity
import com.fasterxml.jackson.databind.{DeserializationFeature, JsonNode, ObjectMapper}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import org.scalatest.{FlatSpec, Matchers}

import scala.collection.JavaConverters._
import scala.io.Source



class IAMServerCertificateLambdaFromString(certFile: String) extends IAMServerCertificateLambda {
  override def getCertFileAsString(s3Entity: S3Entity): String = certFile
}

class IAMServerCertificateLambdaSpec  extends FlatSpec with Matchers {
  val mapper = new ObjectMapper() with ScalaObjectMapper
  mapper.registerModule(DefaultScalaModule).configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

  val mainObj = new IAMServerCertificateLambdaFromString(Source.fromInputStream(getClass.getResourceAsStream("/fake_staged_cert.json")).getLines.mkString)

  def produceS3Event: JsonNode =
    mapper.readValue(Source.fromInputStream( getClass.getResourceAsStream("/sns_s3_event.json") ).getLines.mkString, classOf[JsonNode])

  def toEvent: SNSEvent = {
    val event = new SNSEvent()
    val record = new SNSRecord()
    val sns = new SNS()
    val map = produceS3Event
    sns.setMessage(map.path("Records").get(0).path("Sns").path("Message").asText())
    record.setSns(sns)
    event.setRecords(List[SNSRecord](record))
    event
  }

  "An S3 event" should "run lambda successfully" in {
    val something = mainObj.configureIAMCert(toEvent)
    something.asScala.head shouldBe "Successfully uploaded certificate for ocelotconsulting.com."
  }
} 
开发者ID:ocelotconsulting,项目名称:iam-server-cert-lambda,代码行数:47,代码来源:IAMServerCertificateLambdaSpec.scala

示例13: parseJsValue

//设置package包名称以及导入依赖的类
package webby.form.field
import javax.annotation.Nullable

import com.fasterxml.jackson.databind.JsonNode
import webby.api.Logger
import webby.commons.text.StdStrHtml
import webby.form.{FormErrors, FormResult}

import scala.collection.mutable

trait ValueField[T] extends Field[T] {
  def parseJsValue(node: JsonNode): Either[String, T]

  
  protected def parseJsInt(node: JsonNode)(body: Int => Either[String, T]): Either[String, T] = {
    if (node.isNull || node.asText().isEmpty) Right(nullValue)
    else body(node.asInt())
  }

  def setJsValueAndValidate(@Nullable node: JsonNode): FormResult = {
    if (node != null && !node.isNull) {
      try {
        parseJsValue(node) match {
          case Right(v) => set(v); validate
          case Left(error) => FormErrors(errors = mutable.Map(shortId -> error))
        }
      } catch {
        case e: Exception =>
          Logger(getClass).warn("Error parsing js-value", e)
          FormErrors(errors = mutable.Map(shortId -> form.strings.invalidValue))
      }
    } else {
      setNull
      validate
    }
  }
} 
开发者ID:citrum,项目名称:webby,代码行数:38,代码来源:ValueField.scala

示例14: HiddenBooleanField

//设置package包名称以及导入依赖的类
package webby.form.field
import com.fasterxml.jackson.databind.JsonNode
import webby.form.Form


class HiddenBooleanField(val form: Form, val shortId: String) extends ValueField[Boolean] {
  override def jsField: String = "hidden"
  override def parseJsValue(node: JsonNode): Either[String, Boolean] = parseJsString(node) {v =>
    try Integer.parseInt(v) match {
      case 0 => Right(false)
      case 1 => Right(true)
      case _ => Left(form.strings.invalidValue)
    }
    catch {case e: NumberFormatException => Left(form.strings.enterIntegerNumber)}
  }
  override def nullValue: Boolean = false
} 
开发者ID:citrum,项目名称:webby,代码行数:18,代码来源:HiddenField.scala

示例15: UrlField

//设置package包名称以及导入依赖的类
package webby.form.field
import com.fasterxml.jackson.databind.JsonNode
import webby.commons.text.validator.UrlValidator
import webby.form.{Form, Invalid, Valid, ValidationResult}

class UrlField(val form: Form,
               val shortId: String,
               allowedDomains: Vector[String] = Vector.empty)
  extends ValueField[String] with PlaceholderField[String] {self =>

  var allowedSchemes: Array[String] = Array("http", "https")
  var defaultScheme: String = "http"

  val MaxLength = 250

  // ------------------------------- Reading data & js properties -------------------------------
  override def jsField: String = "text"
  override def parseJsValue(node: JsonNode): Either[String, String] = parseJsString(node)(Right(_))
  override def nullValue: String = null

  
  override def validateFieldOnly: ValidationResult = {
    if (get.length > MaxLength) Invalid(form.strings.noMoreThanCharsError(MaxLength))
    else UrlValidator.validate(get, allowedSchemes = allowedSchemes) match {
      case None => Invalid(form.strings.invalidUrl)
      case Some(url) =>
        if (allowedDomains.nonEmpty && !UrlValidator.validateDomain(url, allowedDomains)) {
          if (allowedDomains.size == 1) return Invalid(form.strings.urlMustContainDomain(allowedDomains.head))
          else return Invalid(form.strings.urlMustContainOneOfDomains(allowedDomains.mkString(", ")))
        }
        Valid
    }
  }
} 
开发者ID:citrum,项目名称:webby,代码行数:35,代码来源:UrlField.scala


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