Scala / Play:无法识别的令牌'非预期' null',' true',' false'或NaN

时间:2016-04-03 11:43:15

标签: json scala playframework

我有Scala型号

case class Model(
  name:          String,
  site:          String,
  phones:        Seq[String],
  duration:      String,
  pricePerMonth: Double,
  address:       String,
  benefits:      Seq[String],
  rating:        Int
)

表示json

{
  "name": "a",
  "site": "b",
  "phones": ["c"],
  "duration": "d",
  "price-per-month": 10.00,
  "address": "e",
  "benefits": ["f"],
  "rating": 1
}

这是我的SBT依赖项:

"com.typesafe.play" %% "play-json" % "2.3.4"

我想用Play解析json。这是我的代码:

val model = fromInputStream { getClass getResourceAsStream "/model.json"
                            } getLines() toString

val json: JsValue = Json.parse(model)

但是我收到了错误

Exception in thread "main" com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'non': was expecting 'null', 'true', 'false' or NaN
 at [Source: java.io.StringReader@a7e666; line: 1, column: 4]
    at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1524)
    at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:557)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._reportInvalidToken(ReaderBasedJsonParser.java:2042)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._reportInvalidToken(ReaderBasedJsonParser.java:2018)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._matchToken(ReaderBasedJsonParser.java:1870)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser.nextToken(ReaderBasedJsonParser.java:657)
    at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:3031)
    at com.fasterxml.jackson.databind.ObjectMapper._readValue(ObjectMapper.java:2951)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:1587)
    at play.api.libs.json.JacksonJson$.parseJsValue(JsValue.scala:486)
    at play.api.libs.json.Json$.parse(Json.scala:19)

任何想法如何解决此错误?

1 个答案:

答案 0 :(得分:0)

这对我有用。来自REPL:

Welcome to Scala version 2.11.7 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_60).
Type in expressions to have them evaluated.
Type :help for more information.

scala> import play.api.libs.json._
import play.api.libs.json._

scala> val json = """
     | {
     |   "name": "a",
     |   "site": "b",
     |   "phones": ["c"],
     |   "duration": "d",
     |   "price-per-month": 10.00,
     |   "address": "e",
     |   "benefits": ["f"],
     |   "rating": 1
     | }
     | """
json: String =
"
{
  "name": "a",
  "site": "b",
  "phones": ["c"],
  "duration": "d",
  "price-per-month": 10.00,
  "address": "e",
  "benefits": ["f"],
  "rating": 1
}
"

scala> Json.parse(json)
res0: play.api.libs.json.JsValue = {"name":"a","site":"b","phones":["c"],"duration":"d","price-per-month":10,"address":"e","benefits":["f"],"rating":1}

所以可能问题来自你的方法:

val model = fromInputStream { getClass getResourceAsStream "/model.json" } getLines() toString