[英]Scala: No Json serializer found for type Any
I have the following code. 我有以下代码。 Here is the schema for vesselFlagCountryDF 这是vesselFlagCountryDF的架构
root
|-- flagcountry: string (nullable = true)
|-- max(count): long (nullable = true)
|-- min(count): long (nullable = true)
|-- avg(count): double (nullable = true)
|-- stddev_samp(count,0,0): double (nullable = false)
And here are some sample rows: 这是一些示例行:
+--------------------+----------+----------+----------+----------------------+
| flagcountry|max(count)|min(count)|avg(count)|stddev_samp(count,0,0)|
+--------------------+----------+----------+----------+----------------------+
| Cyprus| 65| 46| 55.0| 9.40744386111339|
| Luxembourg| 3| 1| 2.5| 0.9999999999999999|
| Niue| 5| 3| 4.4| 0.8944271909999159|
| Palestine| 2| 1| 1.25| 0.49999999999999994|
| Norway| 30| 18| 23.4| 5.683308895353129|
| Mongolia| 21| 15| 17.6| 2.302172886644268|
| Dominica| 1| 1| 1.0| 0.0|
|British Virgin Is...| 1| 1| 1.0| NaN|
+--------------------+----------+----------+----------+----------------------+
Now stddev("count") can either be a Double or Nan. 现在stddev(“ count”)可以是Double或Nan。
import play.api.libs.json.{JsValue, Json}
val vesselFlagCountryDF =
vtype.groupBy("flagcountry").agg(max("count"), min("count"), avg("count"),
stddev("count"))
vesselFlagCountryDF.collect().foreach(row => {
val flagCountry = row.getString(row.fieldIndex("flagcountry"))
val upper: Long = row.getLong(row.fieldIndex("max(count)"))
val lower: Long = row.getLong(row.fieldIndex("min(count)"))
val mean: Double = row.getDouble(row.fieldIndex("avg(count)"))
val stdDevWrapper: Any = row.get(row.fieldIndex("stddev_samp(count,0,0)"))
val stdDev = stdDevWrapper match {
case d: Double => d
case _ => "NaN"
}
val json: JsValue = Json.obj(
"type" -> "statistics",
"name" -> "vesselCountByFlagCountry",
"flagCountry" -> flagCountry,
"timeInterval" -> Json.obj("startTime" -> startTime, "endTime" -> endTime),
"upper" -> upper,
"lower" -> lower,
"mean" -> mean,
"stdDev" -> stdDev
)
On this line: 在这行上:
"stdDev" -> stdDev
I get the following error: 我收到以下错误:
No Json serializer found for type Any. Try to implement an implicit Writes or
Format for this type.
[error] "stdDev" -> stdDev
What is the best way to handle this mistake? 处理此错误的最佳方法是什么?
The following term can only be inferred as Any
as there is no parent type to unify Double
and String
, which is not recommended. 由于没有将Double
和String
统一的父类型,因此以下术语只能推断为Any
,不建议这样做。
val stdDev = stdDevWrapper match {
case d: Double => d
case _ => "NaN"
}
On the other side, the JSON serialization only works with typed values, which not the case of an Any
value. 另一方面,JSON序列化仅适用于类型化值,而Any
值则不适用。
The stdDev
can be refactored to directly write the proper JSON value according the case. 可以重构stdDev
以根据情况直接写入正确的JSON值。
val stdDev: JsValue = stdDevWrapper match {
case d: Double => Json.toJson(d)
case _ => Json.toJson("NaN")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.