[英]How can I automatically map JSON to a case class when a field is a scala keyword?
Within the Play Framework (2.6) ;在Play 框架 (2.6) 内; I am currently automatically mapping JSON to case classes from MongoDB (using ReactiveMongo 0.12 with JSON Collections ).
我目前正在自动将JSON 映射到来自 MongoDB 的案例类(使用ReactiveMongo 0.12和JSON Collections )。 I have downloaded a dataset ( here ) and imported it into MongoDB as a collection in order to do some testing relating to geospatial queries .
我已经下载了一个数据集( 这里)并将它作为一个集合导入到MongoDB中,以便进行一些与地理空间查询相关的测试。 However one of the fields is called " type " (at a quick glance you will see this here ) so I am having issues as this is a keyword in Scala .
然而,其中一个字段称为“类型”(快速浏览您会在此处看到),因此我遇到了问题,因为这是Scala 中的关键字。 This would otherwise be what I would write:
否则我会这样写:
case class Geometry(coordinates: List, type: String)
case class Neighborhood(_id: Option[BSONObjectID], geometry: Geometry, name: String)
Just to add (thanks to @MarioGalic);只是添加(感谢@MarioGalic); declaring scala keywords as class parameter names seems to be done with backticks but I am still having an issue outputting these in the Play templates .
将scala 关键字声明为类参数名称似乎是用反引号完成的,但我仍然遇到在Play 模板中输出这些的问题。 So if I was looping through each document I might write this (which is getting an error).
因此,如果我遍历每个文档,我可能会写这个(这是一个错误)。
@for(ngh <- neighborhoods){
<tr>
...
<td>@ngh.name</td>
<td>@ngh.geometry.`type`</td>
...
</tr>
}
Without backticks doesn't work here and with backticks aren't recognised within the template .没有反引号在这里不起作用,并且模板中无法识别反引号。 I cannot find any other formats in this referenced question/answer on the subject so I am still having an issue.
我在该主题的参考问题/答案中找不到任何其他格式,因此我仍然遇到问题。 Thanks
谢谢
Sorry this is obvious as to what to do.抱歉,这很明显要做什么。 Within the case class model just define a method that has a different name (from "type" in this example but essentially any keyword which is causing an issue:
在案例类模型中,只需定义一个具有不同名称的方法(与本示例中的“type”不同,但本质上是任何导致问题的关键字:
case class Geometry(coordinates: List, `type`: String) {
def getType = `type`
}
Then call this in the template :然后在模板中调用它:
@for(ngh <- neighborhoods){
<tr>
...
<td>@ngh.name</td>
<td>@ngh.geometry.getType</td>
...
</tr>
}
Thanks all!谢谢大家!
You could wrap the field type
with backticks like so:您可以像这样用反引号包裹字段
type
:
case class Geometry(coordinates: List, `type`: String)
The following answer explains backticks syntax in more detail: Need clarification on Scala literal identifiers (backticks)以下答案更详细地解释了反引号语法: 需要澄清 Scala 文字标识符(反引号)
Simply wrap your code in curly braces like this:只需将您的代码用花括号括起来,如下所示:
@{ngh.geometry.`type`}
and the type
field will be properly rendered in the Play template.并且
type
字段将在 Play 模板中正确呈现。 There is no need to create the getType
method.无需创建
getType
方法。
Your full working code would be:您的完整工作代码将是:
@for(ngh <- neighborhoods){
<tr>
...
<td>@ngh.name</td>
<td>@{ngh.geometry.`type`}</td>
...
</tr>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.