0

当我可能不知道我正在解析的文档的确切结构和顺序时,我正在尝试使用 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 中的案例类。

4

1 回答 1

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

于 2011-11-14T03:52:37.543 回答