2016-05-27 87 views
1

这里是日志:如何应对这种日志包含JSON

"V2|ip-10-203-5-16|PSDK_KINESIS_LOG|PSDK_DEFAULT|2016-05-12 00:00:05|VP|aa2ddfdb-4387-49c0-9651-92cc83b8e905|{"vid":"2237031","fdn":"FDNB1995115","type":"0","version":"1.0","device_id":"SCL-TL00_a0-8d-16-e6-39-13_868145026279574","ip":"58.254.0.157","timestamp":1462982395}" 

我的代码:

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 org.slf4j.LoggerFactory 

class JsonLong{ 
    @JsonProperty var fdn: String = null 
    @JsonProperty("type") var typ: String = null 
    @JsonProperty var vid: String = null 
    @JsonProperty var version: String = null 
    @JsonProperty var device_id: String = null 
    @JsonProperty var ip: String = null 
    @JsonProperty var timestamp: Long = 0L 
    override def toString = s"JsonLong(fdn=$fdn, typ=$typ, vid=$vid,version=$version, device_id=$device_id, ip=$ip, timestamp=$timestamp)" 
} 



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

case class log(log_version: String,log_ip: String,log_from: String,SDK: String,action_time: Date,action: String,sn: String,post_code: JsonLong) 

val df = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss") 
val input = sc.textFile("input.snappy") 
val RDD = input.map { line => 
    val p = line.split("\\|") 
    val log_version = p(0) 
    val log_ip = p(1) 
    val log_from = p(2) 
    val SDK = p(3) 
    val action_time = df.parse(p(4)) 
    val action = p(5) 
    val sn = p(6) 
    val post_code = if(p.length==8){ 
    //to read the last JSON 
    jsonString(p(7)) 
    } else("null") 
    log(log_version,log_ip,log_from,SDK,new Date(action_time.getTime()),action,sn,post_code)}.toDF() 

enter image description here

我有最后的Json问题。我已经确定jsonString返回calss JsonLong,但它返回Object。如何处理最后的Json?

回答

0

用来初始化post_code不一定返回一个JsonLong表达:

if(p.length==8) { 
    jsonString(p(7)) // returns JsonLong 
} else("null")  // returns String 

所以,编译器推断,将适合两个结果,在这种情况下java.lang.Object最好的类型。

我假设你打算使用null代替"null",这将解决这个问题:

if(p.length==8) { 
    jsonString(p(7)) // returns JsonLong 
} else { null }  // returns Null, which extends all classes including JsonLong 

这将使编译器推断类型JsonLongpost_code,这应该解决您的问题。

+0

谢谢!但是这里仍然有一个问题,它返回com.fasterxml.jackson.databind.JsonMappingException:找不到类型为[简单类型,类$ line45。$ read $$ iwC $$ iwC $ JsonLong]的合适构造函数:无法从JSON实例化对象(需要添加/启用类型信息?) –

+0

你必须自己弄清楚那个,SO不是一个调试服务... –

+0

Thanks.I刚开始学习Scala ~~我会尽我所能来修复它。 –