2011-11-13 60 views
0

我試圖用lift-json解析JSON文檔,當我可能不知道解析文檔的確切結構和順序時。該文檔包含「對象」列表,全部組織成該對象類型的各個部分,每個部分都爲該類型命名。我玩過各種方式來遍歷類型,對類型名稱進行模式匹配,然後嘗試獲取對象列表,但它似乎從未正常工作。我得到一個空白列表或關於不能找到正確的JSON塊映射到我的案例類的錯誤。使用lift-json解析文檔片段

這裏的一些(幾乎僞)代碼,我來是接近:

case class TypesQueries(queries: Map[String, JValue]); 

case class AddressQueries(addresses: List[AddressQuery]); 
case class AddressQuery(street: String, city: String, state: String, zip: Int) 

case class NameQueries(names: List[NameQuery]); 
case class NameQuery(firstName: String, lastName: String); 

case class EmailQueries(emails: List[EmailQuery]); 
case class EmailQuery(emailAddress: String); 

val jsonData = parse("""{ 
    "queries" : { 
     "addresses" : [ 
      { 
       "street" : "1234 Main St.", 
       "city" : "New York", 
       "state" : "New York", 
       "zip" : 12345 
      }, 
      { 
       "street" : "9876 Broadway Blvd.", 
       "city" : "Chicago", 
       "state" : "IL", 
       "zip" : 23456 
      } 
     ], 
     "names": [ 
      { 
       "firstName" : "John", 
       "lastName" : "Doe" 
      } 
     ], 
     "emails" : [ 
      { 
       "emailAddress" : "[email protected]" 
      }, 
      { 
       "emailAddress" : "[email protected]" 
      } 
     ] 
    } 
}"""); 


val typesQuery = parse(jsonData).extract[TypesQueries]; 

typesQuery.queries.foreach { case(queryType, queryDefinition) => 
    queryType match { 
     case "addresses" => 
      // These extract methods do not work. 
      val addressQueries = queryDefinition.extract[AddressQueries]; 
     case "names" => 
      // These extract methods do not work. 
      val nameQueries = queryDefinition.extract[NameQueries]; 
     case "emails" => 
      // These extract methods do not work. 
      val emailQueries = queryDefinition.extract[EmailQueries]; 
    } 
} 

「地址」,「姓名」和「電子郵件」可能會在任何順序內部「查詢」,並有可能是它們的可變數目。最後,我希望能夠爲相應的類型列表提取對象列表,然後在解析完成後,將各種對象列表傳遞給相應的方法。

所以,問題是:如果我不知道提前完成的文檔結構是什麼,我該如何解析lift-json中的case類。

回答

1

你是非常接近的,這會作用於REPL:

更新

typesQuery.queries.foreach { 
    case(queryType, queryDefinition) => queryType match { 
    case "addresses" => val addressQueries = typesQuery.queries.extract[AddressQueries]; println(addressQueries) 
    case "names" => val nameQueries = typesQuery.queries.extract[NameQueries]; println(nameQueries) 
    case "emails" => val emailQueries = typesQuery.queries.extract[EmailQueries]; println(emailQueries) 
    } 
} 

的想法是,在foreach 「刪除」 包圍每個 「對象」 的名單,所以我們調用typesQuery.queries.extract來幫助案例類匹配我們解析的json

+0

嗯,有沒有辦法避免JObject(List(Field .. noise)?它使我認爲應該是一個非常簡單和直接的位的代碼看起來非常混亂。 –

+0

更新版本如何? – fmpwizard

+0

該版本似乎會生成一個錯誤'net.liftweb.json.MappingException:地址沒有可用值,但我知道你要去哪裏。 –