当json变量时,使用scala lift-json提取case类

时间:2011-11-23 06:04:12

标签: scala lift-json

我正在尝试提取以下json值

// a 'Change item with a list of values
{
      "@count":"2",
      "change":[{
        "@webLink":"http://localhost:8080/viewModification.html?modId=6&personal=false",
        "@version":"b51fde683e206826f32951750ccf34b14bead9ca",
        "@id":"6",
        "@href":"/httpAuth/app/rest/changes/id:6"
      },{
        "@webLink":"http://localhost:8080/viewModification.html?modId=5&personal=false",
        "@version":"826626ff5d6bc95b32c7f03c3357b31e4bf81842",
        "@id":"5",
        "@href":"/httpAuth/app/rest/changes/id:5"
      }]
    }

// a 'Change item with a single value
{
      "@count":"1",
      "change":{
        "@webLink":"http://localhost:8080/viewModification.html?modId=8&personal=false",
        "@version":"803f9c1cd2c553c3b3fb0c950585be868331b3b1",
        "@id":"8",
        "@href":"/httpAuth/app/rest/changes/id:8"
      }
}

我有以下案例类

case class ChangeItem(`@count`: String, change: List[ChangeItemDetail]) {
  def this(`@count`: String, change: ChangeItemDetail) = this(`@count`, List(change))
}
case class ChangeItemDetail(`@webLink`:String, `@version`:String, `@id`:String, `@href`: String)

但是对于lift-json,只有带有多个项目的JSON示例似乎有效,单个项目就会抛出。

      parse(listEx).extract[ChangeItem] // OK
      parse(singleEx).extract[ChangeItem] // throws

有解决方法吗?

1 个答案:

答案 0 :(得分:2)

解决此问题的一种方法是通过将JSON转换为统一格式来“修复”JSON。

val json = parse(origJson) transform { 
  case JField("change", o: JObject) => JField("change", JArray(o :: Nil)) 
}

json.extract[ChangeItem]

这两种情况都适用。