当我可能不知道我正在解析的文档的确切结构和顺序时,我正在尝试使用lift-json解析JSON文档。该文档包含“对象”列表,所有对象都被组织成该对象类型的部分,每个部分都以该类型命名。我已经玩了各种方法来循环类型,类型名称上的模式匹配,然后尝试获取对象列表,但它似乎永远不会正常工作。我得到一个空白列表或错误,无法找到正确的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" : "john.doe@gmail.com"
},
{
"emailAddress" : "david.smith@gmail.com"
}
]
}
}""");
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类。
答案 0 :(得分: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来帮助case类匹配我们解析的json