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

Scala JsonParseException类代码示例

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

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



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

示例1: Slick

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

import java.util.Date

import com.fasterxml.jackson.core.JsonParseException
import play.api.Logger
import play.api.db.DB
import play.api.libs.json.{Json, JsObject}
import slick.driver.MySQLDriver.api._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import play.api.Play.current
object Slick extends Slick {
    def apply(name: String) = new Slick {
        override lazy val DBName = name
    }
}

trait Slick {
    protected lazy val DBName = "default"
    val duration = Duration(5, SECONDS)
    implicit def db = Database.forDataSource(DB.getDataSource(DBName))
}


trait ExtMapper {
    implicit val date2SqlDate = MappedColumnType.base[Date, java.sql.Timestamp](d => new java.sql.Timestamp(d.getTime), d => new java.util.Date(d.getTime))
    implicit val list2String = MappedColumnType.base[List[String], String](array => array.mkString(","), string => string.split(",").toList)
    implicit val jsonObjMapper = MappedColumnType.base[JsObject, String](json => json.toString(), s => try {
        Json.parse(s).as[JsObject]
    } catch {
        case e: JsonParseException => {
            Logger.error(s"JsObjectMapper Error [data:$s]", e)
            Json.obj()
        }
    })

} 
开发者ID:suya55,项目名称:kakaoYellowIdBot,代码行数:39,代码来源:Slick.scala


示例2: JsonParsingSpec

//设置package包名称以及导入依赖的类
import com.fasterxml.jackson.core.JsonParseException
import org.scalatest.{BeforeAndAfterAll, FlatSpecLike, Matchers}
import play.api.libs.json._


class JsonParsingSpec
  extends Matchers
  with FlatSpecLike
  with BeforeAndAfterAll {

  "A json parser" should "be able to parse valid json" in {
    val input = """{
                  	"foo": "bar",
                  	"tags": [1,2,3],
                  		"nested": [{
                  		"fooz": "baz",
                  		"id": 1
                  	}]
                  }"""
    val baz: JsValue = Json.parse(input)
  }

  it should "choke on invalid json" in {
    val input = """{
                  	"foo": "bar",
                  	"tags": [1,2,3],
                  		"nested": [{
                  		"fooz": unquoted text,
                  		"id": 1
                  	}]
                  }"""
    intercept[JsonParseException] {
      val baz: JsValue = Json.parse(input)
    }
  }
} 
开发者ID:rzrelyea,项目名称:scala-akka-web-crawler,代码行数:37,代码来源:JsonParsingSpec.scala


示例3: TopicUtils

//设置package包名称以及导入依赖的类
package com.groupon.dse.kafka.topic

import com.fasterxml.jackson.core.JsonParseException
import org.scalatest.FlatSpec

class TopicUtils$Test extends FlatSpec {

  "The Topic Utils " should "return the list of topics specified in the json" in {
    val contents = "{\"topics\":[{\"name\":\"topic1\",\"metadata\":{\"m1\":\"v1\",\"m2\":\"v2\"}},{\"name\":\"topic2\",\"metadata\":{\"m3\":\"v3\",\"m4\":\"v4\"}},{\"name\":\"topic3\",\"metadata\":{\"m3\":\"v3\",\"m4\":\"v4\"}}]}"
    assert(TopicUtils.extractTopicListFromJson(contents) == Seq(TopicAndMetadata("topic1", Map("m1" -> "v1", "m2" -> "v2")), TopicAndMetadata("topic2", Map("m3" -> "v3", "m4" -> "v4")), TopicAndMetadata("topic3", Map("m3" -> "v3", "m4" -> "v4"))))
  }

  "The Topic Utils " should "return the filtered list if the name key is missing for any topic" in {
    val contents = "{\"topics\":[{\"name\":\"topic1\",\"metadata\":{\"m1\":\"v1\",\"m2\":\"v2\"}},{\"name1\":\"topic2\",\"enabled\":\"false\",\"metadata\":{\"m3\":\"v3\",\"m4\":\"v4\"}},{\"name\":\"topic3\",\"enabled\":\"true\",\"metadata\":{\"m3\":\"v3\",\"m4\":\"v4\"}}],\"extras\":\"test\"}"
    assert(TopicUtils.extractTopicListFromJson(contents) == Seq(TopicAndMetadata("topic1", Map("m1" -> "v1", "m2" -> "v2")), TopicAndMetadata("topic3", Map("m3" -> "v3", "m4" -> "v4"))))
  }

  intercept[JsonParseException] {
    val contents = "invalid_json"
    TopicUtils.extractTopicListFromJson(contents)
  }
} 
开发者ID:groupon,项目名称:baryon,代码行数:23,代码来源:TopicUtils$Test.scala


示例4: handleResponse

//设置package包名称以及导入依赖的类
package com.github.mjreid.flinkwrapper

import com.fasterxml.jackson.core.JsonParseException
import play.api.libs.json._
import play.api.libs.ws.StandaloneWSResponse

trait FlinkResponseHandler {
  def handleResponse[T](response: StandaloneWSResponse)(implicit reads: Reads[T]): T
  def handleResponseWith404[T](response: StandaloneWSResponse)(implicit reads: Reads[T]): Option[T]
  def handleResponseIgnoreStatusCodes[T](response: StandaloneWSResponse)(implicit reads: Reads[T]): T
}

private[flinkwrapper] object FlinkResponseHandler extends FlinkResponseHandler {

  private val maximumBodyCharacters = 4000

  override def handleResponse[T](
    response: StandaloneWSResponse
  )(implicit reads: Reads[T]): T = {
    response.status match {
      case i if i >= 400 =>
        throw FlinkWrapperUnexpectedStatusCodeException(i, response.body.take(maximumBodyCharacters))
      case _ =>
        parseOrThrow(response.body)
    }
  }

  override def handleResponseWith404[T](
    response: StandaloneWSResponse
  )(implicit reads: Reads[T]): Option[T] = {
    response.status match {
      case 404 =>
        None
      case i if i >= 400 =>
        throw FlinkWrapperUnexpectedStatusCodeException(i, response.body.take(maximumBodyCharacters))
      case _ =>
        Some(parseOrThrow(response.body))
    }
  }

  override def handleResponseIgnoreStatusCodes[T](
    response: StandaloneWSResponse
  )(implicit reads: Reads[T]): T = {
    parseOrThrow(response.body)
  }

  private[flinkwrapper] def parseOrThrow[T](
    responseBody: String
  )(implicit reads: Reads[T]): T = {
    try {
      val json: JsValue = Json.parse(responseBody)
      json.validate[T] match {
        case JsSuccess(validatedObject, _) => validatedObject
        case JsError(errors) => throw FlinkWrapperInvalidJsonException(errors.mkString("; "))
      }
    } catch {
      case e: JsonParseException => throw FlinkWrapperInvalidJsonException("Response was not valid JSON", e)
    }
  }
} 
开发者ID:mjreid,项目名称:flink-rest-scala-wrapper,代码行数:61,代码来源:FlinkResponseHandler.scala


示例5: WorkExtractorTest

//设置package包名称以及导入依赖的类
package uk.ac.wellcome.platform.idminter.steps

import com.fasterxml.jackson.core.JsonParseException
import org.scalatest.concurrent.{IntegrationPatience, ScalaFutures}
import org.scalatest.{FunSpec, Matchers}
import uk.ac.wellcome.models.aws.SQSMessage
import uk.ac.wellcome.models.{SourceIdentifier, Work}
import uk.ac.wellcome.utils.JsonUtil

class WorkExtractorTest
    extends FunSpec
    with Matchers
    with ScalaFutures
    with IntegrationPatience {

  it("extracts the work included in the SQS message") {

    val miroID = "M0000001"
    val title = "A note about a narwhal"

    val work = Work(
      identifiers = List(SourceIdentifier("Miro", "MiroId", miroID)),
      title = title
    )
    val sqsMessage = SQSMessage(Some("subject"),
                                JsonUtil.toJson(work).get,
                                "topic",
                                "messageType",
                                "timestamp")

    val eventualWork = WorkExtractor.toWork(sqsMessage)

    whenReady(eventualWork) { extractedWork =>
      extractedWork.identifiers.head.value shouldBe miroID
      extractedWork.title shouldBe title
    }
  }

  it(
    "should return a failed future if it fails parsing the message it receives") {
    val sqsMessage = SQSMessage(Some("subject"),
                                "not a json string",
                                "topic",
                                "messageType",
                                "timestamp")

    val eventualWork = WorkExtractor.toWork(sqsMessage)

    whenReady(eventualWork.failed) { e =>
      e shouldBe a[JsonParseException]
    }
  }

} 
开发者ID:wellcometrust,项目名称:platform-api,代码行数:55,代码来源:WorkExtractorTest.scala


示例6: ParserTest

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

import io.buoyant.test.FunSuite
import com.fasterxml.jackson.core.JsonParseException

class ParserTest extends FunSuite {

  abstract class SubConfig extends PolymorphicConfig

  class AConfig extends PolymorphicConfig
  class ASubConfig extends SubConfig
  class BConfig extends PolymorphicConfig

  class A1 extends ConfigInitializer {
    val configClass = classOf[AConfig]
    override val configId = "io.l5d.a"
  }

  class A2 extends ConfigInitializer {
    val configClass = classOf[ASubConfig]
    override val configId = "io.l5d.a"
  }

  class B extends ConfigInitializer {
    val configClass = classOf[BConfig]
    override val configId = "io.l5d.b"
  }

  test("allows different ids for the same parent config class") {
    val _ = Parser.objectMapper("{}", Seq(Seq(new A1(), new B())))
  }

  test("disallows same id for same parent config class") {
    assertThrows[ConflictingSubtypes] {
      val _ = Parser.objectMapper("{}", Seq(Seq(new A1(), new A1())))
    }
  }

  test("allows same id for different parent config classes") {
    val _ = Parser.objectMapper("{}", Seq(Seq(new A1(), new A2())))
  }

  test("allows same id for different initializers") {
    val _ = Parser.objectMapper("{}", Seq(Seq(new A1()), Seq(new A1())))
  }

  test("errors on duplicated properties") {

    val mapper = Parser.objectMapper("{}", Nil)
    assertThrows[JsonParseException] {
      val foo = mapper.readValue[Foo]("""{"a": 5, "a": 7}""")
    }
  }
}

case class Foo(a: Int) 
开发者ID:linkerd,项目名称:linkerd,代码行数:57,代码来源:ParserTest.scala


示例7: CustomBigDecimalDeserialiserModule

//设置package包名称以及导入依赖的类
package cjp.catalogue.conf

import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.core.{JsonToken, JsonParseException, JsonParser}
import com.fasterxml.jackson.databind.{DeserializationContext}
import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer
import scala.util.{Failure, Success, Try}

class CustomBigDecimalDeserialiserModule extends SimpleModule("CustomBigDecimalDeserialiserModule") {
  addDeserializer(classOf[BigDecimal], BigDecimalDeserializer)
}

object BigDecimalDeserializer extends StdScalarDeserializer[BigDecimal](classOf[BigDecimal]) {

  override def deserialize(jsonParser: JsonParser, context: DeserializationContext): BigDecimal = {
    Option(jsonParser.getValueAsString) match {
      case Some(str: String) => Try(BigDecimal(str)) match {
        case Success(value) => value
        case Failure(error) => throw new JsonParseException(s"Unable to parse ${str} to BigDecimal", jsonParser.getCurrentLocation, error)
      }
      case None if jsonParser.getCurrentToken == JsonToken.VALUE_NULL => null.asInstanceOf[BigDecimal]
      case _ => throw new JsonParseException(s"Expected a string token representing type 'BigDecimal', found: ${jsonParser.getCurrentToken}", jsonParser.getCurrentLocation)
    }
  }
} 
开发者ID:UKHomeOffice,项目名称:product-catalogue,代码行数:26,代码来源:CustomBigDecimalSerialiserModule.scala


示例8: ObjectWordSpec

//设置package包名称以及导入依赖的类
package pl.writeonly.son2.jack.providers

import com.fasterxml.jackson.core.JsonParseException
import com.fasterxml.jackson.databind.JsonMappingException
import pl.writeonly.son2.core.liners.{Liner, LinerOpt}
import pl.writeonly.son2.core.providers.Provider
import pl.writeonly.son2.jack.chain.ChainNotationPairJack
import pl.writeonly.son2.jack.core.Formats
import pl.writeonly.son2.spec.WhiteResultSpec

class ObjectWordSpec extends WhiteResultSpec {

  val provider: Provider = ChainNotationPairJack(Formats.OBJECT)
  "A Provider" should {
    "produce JsonParseException when convert a" in {
      assertThrows[JsonParseException] {
        provider.convert("a")
      }
    }
    "produce JsonMappingException when convert empty string" in {
      assertThrows[JsonMappingException] {
        provider.convert("")
      }
    }
  }

  val liner: Liner = new LinerOpt(provider)
  "A Liner" should {
    "return empty comment" in {
      assertResult(provider.comment("") + "\n")(liner.apply(""))
    }
  }
} 
开发者ID:writeonly,项目名称:son2,代码行数:34,代码来源:ObjectWordSpec.scala


示例9: JavaPropsWordSpec

//设置package包名称以及导入依赖的类
package pl.writeonly.son2.jack.providers

import com.fasterxml.jackson.core.JsonParseException
import com.fasterxml.jackson.databind.JsonMappingException
import pl.writeonly.son2.core.liners.{Liner, LinerOpt}
import pl.writeonly.son2.core.providers.Provider
import pl.writeonly.son2.jack.chain.ChainNotationPairJack
import pl.writeonly.son2.jack.core.Formats
import pl.writeonly.son2.spec.WhiteResultSpec

class JavaPropsWordSpec extends WhiteResultSpec {

  val provider: Provider = ChainNotationPairJack(Formats.JAVA_PROPS)
  "A Provider" should {
    "produce JsonParseException when convert a" in {
      assertThrows[JsonParseException] {
        provider.convert("a")
      }
    }
    "produce JsonMappingException when convert empty string" in {
      assertThrows[JsonMappingException] {
        provider.convert("")
      }
    }
  }

  val liner: Liner = new LinerOpt(provider)
  "A Liner" should {
    "return empty comment" in {
      assertResult(provider.comment("") + "\n")(liner.apply(""))
    }
  }
} 
开发者ID:writeonly,项目名称:son2,代码行数:34,代码来源:JavaPropsWordSpec.scala


示例10: XmlWordSpec

//设置package包名称以及导入依赖的类
package pl.writeonly.son2.jack.providers

import com.fasterxml.jackson.core.JsonParseException
import com.fasterxml.jackson.databind.JsonMappingException
import pl.writeonly.son2.core.liners.{Liner, LinerOpt}
import pl.writeonly.son2.core.providers.Provider
import pl.writeonly.son2.jack.chain.ChainNotationPairJack
import pl.writeonly.son2.jack.core.Formats
import pl.writeonly.son2.spec.WhiteResultSpec

class XmlWordSpec extends WhiteResultSpec {

  val provider: Provider = ChainNotationPairJack(Formats.XML)
  "A Provider" should {
    "produce JsonParseException when convert a" in {
      assertThrows[JsonParseException] {
        provider.convert("a")
      }
    }
    "produce JsonMappingException when convert empty string" in {
      assertThrows[JsonMappingException] {
        provider.convert("")
      }
    }
    "produce JsonMappingException when convert []" in {
      assertThrows[JsonMappingException] {
        provider.convert("[]")
      }
    }
    "produce JsonMappingException when convert [0,1]" in {
      assertThrows[JsonMappingException] {
        provider.convert("[0,1]")
      }
    }
  }

  val liner: Liner = new LinerOpt(provider)
  "A Liner" should {
    "return empty comment" in {
      assertResult(provider.comment("") + "\n")(liner.apply(""))
    }
  }
} 
开发者ID:writeonly,项目名称:son2,代码行数:44,代码来源:XmlWordSpec.scala


示例11: YamlWordSpec

//设置package包名称以及导入依赖的类
package pl.writeonly.son2.jack.providers

import com.fasterxml.jackson.core.JsonParseException
import com.fasterxml.jackson.databind.JsonMappingException
import pl.writeonly.son2.core.liners.{Liner, LinerOpt}
import pl.writeonly.son2.core.providers.Provider
import pl.writeonly.son2.jack.chain.ChainNotationPairJack
import pl.writeonly.son2.jack.core.Formats
import pl.writeonly.son2.spec.WhiteResultSpec

class YamlWordSpec extends WhiteResultSpec {

  val provider: Provider = ChainNotationPairJack(Formats.YAML)
  "A Provider" should {
    "produce JsonParseException when convert a" in {
      assertThrows[JsonParseException] {
        provider.convert("a")
      }
    }
    "produce JsonMappingException when convert empty string" in {
      assertThrows[JsonMappingException] {
        provider.convert("")
      }
    }
  }

  val liner: Liner = new LinerOpt(provider)
  "A Liner" should {
    "return empty comment" in {
      assertResult(provider.comment("") + "\n")(liner.apply(""))
    }
  }
} 
开发者ID:writeonly,项目名称:son2,代码行数:34,代码来源:YamlWordSpec.scala


示例12: CsvWordSpec

//设置package包名称以及导入依赖的类
package pl.writeonly.son2.jack.providers

import com.fasterxml.jackson.core.JsonParseException
import com.fasterxml.jackson.databind.JsonMappingException
import pl.writeonly.son2.core.liners.{Liner, LinerOpt}
import pl.writeonly.son2.core.providers.Provider
import pl.writeonly.son2.jack.chain.ChainNotationPairJack
import pl.writeonly.son2.jack.core.Formats
import pl.writeonly.son2.spec.WhiteResultSpec

class CsvWordSpec extends WhiteResultSpec {

  val provider: Provider = ChainNotationPairJack(Formats.CSV)
  "A Provider" should {
    "produce JsonParseException when convert a" in {
      assertThrows[JsonParseException] {
        provider.convert("a")
      }
    }
    "produce JsonMappingException when convert empty string" in {
      assertThrows[JsonMappingException] {
        provider.convert("")
      }
    }
  }

  val liner: Liner = new LinerOpt(provider)
  "A Liner" should {
    "return empty comment" in {
      assertResult(provider.comment("") + "\n")(liner.apply(""))
    }
  }
} 
开发者ID:writeonly,项目名称:son2,代码行数:34,代码来源:CsvWordSpec.scala


示例13: getRecos

//设置package包名称以及导入依赖的类
package com.gravity.gdk.placement

import com.fasterxml.jackson.core.JsonParseException
import com.gravity.gdk.config.DefaultSettings
import com.gravity.gdk.reco.{RecoContext, RecoResult}

import scala.collection.mutable
import scala.concurrent._
import scalaj.http.{BaseHttp, Http}


  def getRecos(
    limit: Int = 0,
    bucketNumber: Int = 0,
    logImpression: Boolean = true
  )(implicit recoCtx: RecoContext, http: BaseHttp = Http, ec: ExecutionContext): Future[RecoResult] = Future {
    val params = mutable.HashMap(
      "placement" -> key.placementId.toString,
      "userguid" -> recoCtx.user.userGuid,
      "url" -> recoCtx.currentUrl,
      "_" -> System.currentTimeMillis().toString,
      "pageViewGuid" -> recoCtx.pageViewGuid.guid
    )

    if(limit > 0)
      params += "limit" -> limit.toString

    if(recoCtx.imageWidth > 0)
      params += "imageWidth" -> recoCtx.imageWidth.toString

    if(recoCtx.imageHeight > 0)
      params += "imageHeight" -> recoCtx.imageHeight.toString

    if(bucketNumber > 0)
      params += "bucket" -> bucketNumber.toString

    if(!logImpression)
      params += "logResult" -> "0"

    val response = http(DefaultSettings.apiRecosUrl(key.placementId)).params(params.toMap).asString

    if(response.isSuccess) {
      try {
        RecoResult.fromApiResponse(response) match {
          case Left(errors) =>
            throw PlacementGetRecosResponseFormatException(errors)

          case Right(recoResult) =>
            recoResult
        }
      }
      catch {
        case ex: JsonParseException => throw PlacementGetRecosResponseJsonParseException(ex)
      }
    }
    else
      throw PlacementGetRecosBadHttpStatusException(response.code)
  }
} 
开发者ID:GravityLabs,项目名称:gdk-scala,代码行数:60,代码来源:Placement.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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