Scala:找不到类型[simple type,class Thing]的合适构造函数:无法从JSON对象实例化

时间:2016-05-30 08:31:56

标签: json scala jackson

我曾尝试测试以下代码来阅读Json,但这是假的。

import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.core.JsonParseException
import com.fasterxml.jackson.databind.ObjectMapper
import org.apache.spark.{SparkContext, SparkConf}
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonCreator; 
import java.sql.Date
import java.text.SimpleDateFormat
import org.slf4j.LoggerFactory


@JsonCreator
case class JsonLong{
  @JsonProperty("fdn") var fdn: String = null
  @JsonProperty("type") var tpy: String= null
  @JsonProperty("vid") var vid: String = null
  @JsonProperty("version") var version: String = null
  @JsonProperty("device_id") var device_id: String = null
  @JsonProperty("ip") var ip: String = null
  @JsonProperty("timestamp") var timestamp: Long = 0L
}


def jsonString(logjson:String):JsonLong ={
    val mapper = new ObjectMapper()
    val record = mapper.readValue(logjson, classOf[JsonLong])
    record
  }


val jsoninput = "{\"fdn\":\"FDNB2023750\",\"type\":\"0\",\"vid\":\"2246195\",\"version\":\"1.0\",\"device_id\":\"HM+NOTE+1TD_0c-1d-af-7e-1e-a3_865813020970745\",\"ip\":\"106.118.164.215\",\"timestamp\":1463847764}"


val jsonRDD =   jsonString(jsoninput)

这是我想读的Json: “{\” FDN \ “:\” FDNB2023750 \” \ “类型\”:\ “0 \”,\ “VID \”:\ “2246195 \”,\ “版本\”:\ “1.0 \”, \ “DEVICE_ID \”:\ “HM +注+ 1TD_0c-1D-AF-7E-1E-a3_865813020970745 \”,\ “IP \”:\ “106.118.164.215 \”,\ “时间戳\”:1463847764}“< / p>

我收到以下回复: enter image description here

我知道'type'是Scala中的关键字。所以,我尝试使用@JsonProperty.It是我的代码是对的?或者类JsonLong还有其他问题吗?

1 个答案:

答案 0 :(得分:1)

我找到了一种处理此日志的方法。但是不要使用jackson,使用json4s来捕获关键值。

import org.json4s._
import org.json4s.jackson.JsonMethods._

implicit val formats = DefaultFormats 

case class JsonLong(
  var fdn: String=null,
  var `type`: String=null, 
  var vid: String=null,
  var version: String=null,
  var device_id: String=null,
  var ip: String=null,
  var timestamp: Long=0L
)

val jsoninput = "{\"fdn\":\"FDNB2023750\",\"type\":\"0\",\"vid\":\"2246195\",\"version\":\"1.0\",\"device_id\":\"HM+NOTE+1TD_0c-1d-af-7e-1e-a3_865813020970745\",\"ip\":\"106.118.164.215\",\"timestamp\":1463847764}"
val jsontest = parse(jsoninput, useBigDecimalForDouble = true)
    jsontest.extract[JsonLong]