View Javadoc
1   /*
2    * Licensed under the Apache License, Version 2.0 (the "License");
3    * you may not use this file except in compliance with the License.
4    * You may obtain a copy of the License at
5    *
6    * http://www.apache.org/licenses/LICENSE-2.0
7    *
8    * Unless required by applicable law or agreed to in writing, software
9    * distributed under the License is distributed on an "AS IS" BASIS,
10   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11   * See the License for the specific language governing permissions and
12   * limitations under the License.
13   */
14  package com.addthis.codec.jackson;
15  
16  import java.io.IOException;
17  
18  import com.fasterxml.jackson.core.JsonParser;
19  import com.fasterxml.jackson.core.JsonProcessingException;
20  import com.fasterxml.jackson.core.ObjectCodec;
21  import com.fasterxml.jackson.databind.BeanDescription;
22  import com.fasterxml.jackson.databind.DeserializationContext;
23  import com.fasterxml.jackson.databind.JsonDeserializer;
24  import com.fasterxml.jackson.databind.ObjectMapper;
25  import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler;
26  import com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition;
27  
28  public class WriteonlyPropertyIgnorer extends DeserializationProblemHandler {
29  
30      @Override
31      public boolean handleUnknownProperty(DeserializationContext ctxt,
32                                           JsonParser jp,
33                                           JsonDeserializer<?> deserializer,
34                                           Object beanOrClass,
35                                           String propertyName) throws IOException, JsonProcessingException {
36          ObjectCodec objectCodec = jp.getCodec();
37          if (objectCodec instanceof ObjectMapper) {
38              ObjectMapper objectMapper = (ObjectMapper) objectCodec;
39              BeanDescription beanDescription =
40                      objectMapper.getSerializationConfig().introspect(ctxt.constructType(beanOrClass.getClass()));
41              for (BeanPropertyDefinition propertyDefinition : beanDescription.findProperties()) {
42                  if (propertyName.equals(propertyDefinition.getName())) {
43                      jp.skipChildren();
44                      return true;
45                  }
46              }
47          }
48          return false;
49      }
50  }