如何正确使用 Jackson ObjectMapper 来解析播放控制器中收到的 JSON?

How do I properly use a Jackson ObjectMapper to parse JSON received in a play controller?

我使用 Jackson ObjectMapper 生成这样的域 类:

  /**
   * Allows adding a feature to a collection
   *
   * @param collectionId The ID of the feature collection this feature should be added to
   * @return The JSON representation of the feature persisted (including any data generated during insertion)
   */
  def addFeatureToCollection(collectionId: String) = Action { request =>
    if (geoDataPersistenceService.collectionExistsAndIsPublic(collectionId)) {
      request.body.asJson match {
        case Some(json) => {
          try {
            val f: Feature = new ObjectMapper().readValue(json.toString, classOf[Feature])
            Ok(geoDataPersistenceService.add(f, collectionId))
          } catch {
            case jme: JsonMappingException => BadRequest("Can't map the received JSON to a feature")
          }
        }
        case None => BadRequest("No text body received")
      }
    } else {
      NotFound("No collection by that name")
    }
  }

我知道在 Play 中首选的方式是使用 ScalaJsonCombinators 但在那种情况下我想坚持使用 ObjectMapper,因为它是一个非常先进且经过良好测试的实现。

如何避免使用 request.body.asJson 解析收到的 JSON 然后使用 toString 方法序列化它然后使用 ObjectMapper 再次解析它的无用弯路?

看看BodyParsers。正确的方法是实现你自己的基于 jackson 的 BodyParser。