如何在Play 2.1中处理JSON解析中的可选字段 [英] How to handle optional fields in JSON parsing in play 2.1

查看:68
本文介绍了如何在Play 2.1中处理JSON解析中的可选字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用新的Play 2.1-RC1框架,并且我有一个带有Option []字段的类,如下所示:

I'm using the new Play 2.1-RC1 framework and I have a class that has an Option[] field, something like this:

import play.api.libs.json._
import play.api.libs.json.util._
import play.api.libs.json.Reads._
import play.api.libs.json.Writes._
import play.api.libs.json.Format._
import play.api.libs.functional.syntax._

case class Test(name: String, value: Option[String])

object Test {
  implicit val testFormat = (
    (__ \ "name").format[String] and
    (__ \ "value").format[Option[String]] 
  )(Test.apply, unlift(Test.unapply))
  def fromJson(js: String): Test = {
    Json.fromJson[Test](Json.parse(js)).fold(
        valid   = { t => t},
        invalid = { e => {
          val missingField = (e(0)._1).toString.substring(1)
          val badJs = js.trim
          val newJs = badJs.substring(0, badJs.length()-1)+",\""+missingField+"\":null}"
          fromJson(newJs)
        }} 
    )
  }
}

我希望能够处理忽略可选值"数据的JSON字符串,例如

I want to be able to handle JSON strings that omit the optional "value" data, e.g.

val y = """{"name":"someone"}"""

(已编辑问题) 我可以按照验证步骤所示重写json字符串(相当笨拙),但是 有没有一种更简单的模式可以为缺少的Optional字段提供None?请注意,此重写不适用于嵌套结构,或者不能简单地附加缺少的字段的任何地方.

(edited question) I can rewrite the json string (rather clumsily) as shown in the validation step, but is there a simpler pattern I can use to supply None for missing Optional fields? Note that this rewrite does not work with nested structures, or anywhere where I can't simply append the missing field.

推荐答案

您可以简单地执行以下操作:

You can simply do this:

import play.api.libs.json._
import play.api.libs.functional.syntax._

case class Test(name: String, value: Option[String])

implicit val testFormat = Json.format[Test]

def hoge = Action(Json.parse.json) { request => 
    Json.fromJson[Test](request.body)
    ...
}

这篇关于如何在Play 2.1中处理JSON解析中的可选字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆