使用lift-json解析文档片段



当我可能不知道我正在解析的文档的确切结构和顺序时,我试图用lift-json解析JSON文档。该文档包含一个"对象"列表,所有这些对象都被组织成该对象类型的部分,每个部分都以该类型命名。我尝试了各种方法来循环类型,在类型名称上进行模式匹配,然后试图得到对象列表,但它似乎从来没有正常工作过。我要么得到一个空白列表,要么得到一个关于无法找到适当的JSON块映射到我的case类的错误。

这里有一些(几乎是伪)代码,这是我所做的最接近的:

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];
    }
}

"地址"、"姓名"one_answers"电子邮件"可以在"查询"中以任意顺序出现,并且它们的数量可能是可变的。

最后,我希望能够为各自的类型列表提取对象列表,然后,一旦解析完成,将各种对象列表传递给适当的方法。

所以,问题是:如果我不知道完整的文档结构将是什么,我如何在lift-json中解析成case类。

您非常接近,这在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

相关内容

  • 没有找到相关文章