2014-04-17 24 views
0

我需要分析以下JSON字符串JSON解析工作:JsonProperty标注没有在斯卡拉(杰克逊/ Jerkson)

{"type": 1}

我使用看起来像案例类:

case class MyJsonObj(
    val type: Int 
) 

然而,这会让Scala感到困惑,因为'type'是一个关键字。所以,我尝试使用@JsonProperty注释从Jacson/Jerkson如下:

case class MyJsonObj(
    @JsonProperty("type") val myType: Int 
) 

然而,JSON分析器仍拒绝以寻找JSON而不是“的myType”类型'字符串。下面的示例代码说明问题:

import com.codahale.jerkson.Json._ 
import org.codehaus.jackson.annotate._ 

case class MyJsonObj(
    @JsonProperty("type") val myType: Int 
) 

object SimpleExample { 
    def main(args: Array[String]) { 
    val jsonLine = """{"type":1}""" 
    val JsonObj = parse[MyJsonObj](jsonLine) 
} 

我得到以下错误:

[error] (run-main-a) com.codahale.jerkson.ParsingException: Invalid JSON. Needed [myType], but found [type]. 

PS:从上面可以看出,我使用jerkson /杰克逊,但不会介意切换到其他一些JSON解析库,如果这使生活更容易。

回答

3

使用后引号,以防止Scala编译器从解释型为关键字:

case class MyJsonObj(
    val `type`: Int 
) 
+0

虽然将工作添加斯卡拉支持对象映射器,我真的在寻找@JsonProperty注释没有按预期工作的原因。另外,我希望val的名字比'type'更有意义。 – gjain

+0

这可能是Scala使所有字段私有并自动生成getter和setter方法的问题。您可以使用Scala的[元注释](http://www.scala-lang.org/api/current/index.html#scala.annotation.meta.package)。如果用@ @(JsonProperty(“type”)@field @getter @setter)替换'@JsonProperty(“type”)''会发生什么? – wingedsubmariner

1

我怀疑你是不是能够在杰克逊斯卡拉支持正常。

我已经试过这样:

object Test extends App { 

    val mapper = new ObjectMapper 
    mapper.registerModule(DefaultScalaModule) 
    println(mapper.writeValueAsString(MyJsonObj(1))) 

    val obj = mapper.readValue("""{"type":1}""", classOf[MyJsonObj]) 
    println(obj.myType) 
} 

case class MyJsonObj(@JsonProperty("type") myType: Int) 

我也得到:

{"type":1} 
1 

请注意,我通过调用registerModule