title: Conditionally serialize collection field best practice?
body: <p>I already have a solution to my problem, I'll describe it later, but I don't like it that's why I ask.</p>
  
  <p>I'm using newest libraries of jersey and jackson. I have a rest service for an entity, so far, I have 2 get methods: getById and getList, both return json using jackson. The entity refers to itself using OneToMany relationship so it's a set of entities. For getList i don't want that field to be serialized and for getById I want it to be serialized but in my own way.</p>
  
  <p>My solution is:</p>
  
  <p>For getList I use view on a field
  In entity bean I use my JsonView class FirstLevelOfCollection:</p>
  
  <pre><code>@JsonView(JacksonViews.FirstLevelOfCollection.class)
  </code></pre>
  
  <p>In rest service getList method, I use Object as a view filter so all all field without @JsonView will be included:</p>
  
  <pre><code>ObjectMapper mapper = new ObjectMapper();
  resultString = mapper.writerWithView(Object.class).writeValueAsString(resultObject);
  </code></pre>
  
  <p>For getById I use custom serialize</p>
  
  <pre><code>ObjectMapper mapper = new ObjectMapper();
  SimpleModule testModule = new SimpleModule("MyModule", new Version(1, 0, 0, null, null, null));
  testModule.addSerializer(Set.class, new EndEventCodesSerializer(Set.class));
  mapper.registerModule(testModule);
  resultString  = mapper.writeValueAsString(resultObject);
  </code></pre>
  
  <p>I can't use @JsonIgnore insted of view because then custom serialize will not see it too. It works but it seems weird and ugly especially to exclude field like that, what I also wanted to achieve but I don't know how is to use an exclusion(getList behavior) by default for all future request. Can I have a better solution?</p>