我试图提取以下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类
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
有解决办法吗?
解决这个问题的一种方法是通过将JSON转换为统一的格式来"修复"JSON。
val json = parse(origJson) transform {
case JField("change", o: JObject) => JField("change", JArray(o :: Nil))
}
json.extract[ChangeItem]