Scala中的Gson:序列化Json输出中的额外字段`bitmap $ 0`

时间:2018-01-24 14:10:20

标签: scala gson

我在Scala中使用Gson来序列化一个简单的Scala类:

case class Statistics(source: String,
                      count: Integer,
                      sum: Double,
                      average: Double,
                      median: Double,
                      maximum: Double,
                      minimum: Double) {
  def toJson: JsonElement = Config.GSON.toJsonTree(this)
  [...]
}

GSON在单独的对象Config中定义:

lazy val GSON: Gson = new GsonBuilder()
.setPrettyPrinting()
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.disableHtmlEscaping()
.create()

toJson的输出看起来像预期的那样:

{
"Source": "test",
"Count": 45,
"Sum": 38.73403662,
"Average": 0.8607563693333333,
"Median": 0.60809594,
"Maximum": 2.5913415,
"Minimum": 0.418911,
},

现在我想使用Statistics添加LazyLogging类的一些日志记录:

import com.typesafe.scalalogging.LazyLogging

case class Statistics(source: String,
                      count: Integer,
                      sum: Double,
                      average: Double,
                      median: Double,
                      maximum: Double,
                      minimum: Double) extends LazyLogging {
  def toJson: JsonElement = Config.GSON.toJsonTree(this)
  [...]
}

现在toJson的输出会获得一个额外的字段Bitmap$0

{
"Source": "test",
"Count": 45,
"Sum": 38.73403662,
"Average": 0.8607563693333333,
"Median": 0.60809594,
"Maximum": 2.5913415,
"Minimum": 0.418911,
"Bitmap$0": false
},

我尝试通过调整this recipe from the Gson docs来排除为特定类添加排除策略:

class SpecificClassExclusionStrategy(excludedThisClass: Class[_]) extends ExclusionStrategy {

  import com.google.gson.FieldAttributes

  def shouldSkipClass(clazz: Class[_]): Boolean = excludedThisClass == clazz

  def shouldSkipField(f: FieldAttributes): Boolean = excludedThisClass == f.getDeclaredClass
}

并将其添加到GSON对象:

lazy val GSON: Gson = new GsonBuilder()
.setPrettyPrinting()
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.disableHtmlEscaping()
.addSerializationExclusionStrategy(new SpecificClassExclusionStrategy(classOf[LazyLogging]))
.create()

但这并没有什么不同。 因此,我的第一个问题是:朦胧的Bitmap$0字段在哪里首先出现。 第二个是:我如何阻止Gson序列化呢?

1 个答案:

答案 0 :(得分:0)

排除策略并不意味着过滤超类;它作用于字段和对象(字段的值)。

您应该使用以下内容:

class SpecificFieldExclusionStrategy() extends ExclusionStrategy {

  import com.google.gson.FieldAttributes

  def shouldSkipClass(clazz: Class[_]): Boolean = false

  def shouldSkipField(f: FieldAttributes): Boolean = f.getName == "bitmap$0"
}

关于位图$ 0,在另一个问题中回答:In compiled Scala, what is the bitmap$0 field?