2015-04-07 91 views
0

我想在下面的示例中排除_passthroughFields属性。当我使用调试器时,它看起来像我的PropertyFilter从不使用。我究竟做错了什么?如何排除Jackson json序列化(Scala)中的字段

import java.util 

import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter.SerializeExceptFilter 
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider 
import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper, ObjectWriter} 
import com.fasterxml.jackson.module.scala.DefaultScalaModule 
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper 
import org.scalatest.{Matchers, WordSpec} 

import scala.collection.immutable.Map 

class PassthroughFieldsSpec extends WordSpec with Matchers { 
    "JacksonParser" when { 
    "given an Object and undesired fields" should { 
     "not include those fields in the json response" in { 
     trait Foo { 
      def id: String 
      def _passthroughFields: Map[String, String] = Map.empty 
     } 

     class Bar(val id: String, override val _passthroughFields: Map[String, String]) extends Foo 

     val item = new Bar("abcd", Map.empty) 

     val mapper = new ObjectMapper() with ScalaObjectMapper 
     mapper.registerModule(DefaultScalaModule) 
     mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) 

     val excludes = new util.HashSet[String](1) 
     excludes.add("_passthroughFields") 
     excludes.add("get_passthroughFields") 

     val filters = new SimpleFilterProvider() 
      .addFilter("filter properties by name", new SerializeExceptFilter(excludes)) 

     val writer: ObjectWriter = mapper.writer(filters) 

     val json = writer.writeValueAsString(item) 
     json.contains("_passthroughFields") shouldBe false 
     } 
    } 
    } 
} 
+0

那么,我跑你的测试场景,它成功通过。你为什么认为过滤器被忽略 –

+0

我运行它时不起作用。 json变量包含'{“id”:“abcd”,“_ passthroughFields”:{}}'并且仍然包含'_passthroughFields',它应该被排除。 (针对jackson-module-scala 2.5.1和scalatest 2.2.4运行) – reikje

回答

1

我想你可以使用@JsonIgnore之类的东西来排除它,或者使字段暂态。

否则,如果您需要在案例类代码之外定义它(例如您的示例),您可以使用Genson来完成。

import com.owlike.genson._ 
import com.owlike.genson.reflect.VisibilityFilter 

// Note that if you use case classes you don't need the visibility filter stuff 
// it is used to indicate that private fields should be ser/de 
val genson = new GensonBuilder() 
    .withBundle(ScalaBundle()) 
    .useFields(true, VisibilityFilter.PRIVATE) 
    .exclude("_passthroughFields") 
    .create() 

genson.toJson(item) 

声明:我是Gensons作者。

+0

是的,该类不在我的控制之下。这是一个由scrooge-sbt-plugin(Thrift)生成的类。我会试试Genson,看起来非常好 - 谢谢! – reikje

+0

太棒了,如果您遇到任何问题,请不要犹豫,在邮件列表或github上举报 – eugen

相关问题