View Javadoc
1   /*
2    * Copyright 2015-2022 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.bremersee.geojson.converter.deserialization;
18  
19  import static java.util.Objects.isNull;
20  
21  import com.fasterxml.jackson.core.JsonParser;
22  import com.fasterxml.jackson.core.type.TypeReference;
23  import com.fasterxml.jackson.databind.DeserializationContext;
24  import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
25  import java.io.IOException;
26  import java.io.Serial;
27  import java.util.Map;
28  import org.bremersee.geojson.GeoJsonGeometryFactory;
29  import org.locationtech.jts.geom.Geometry;
30  import org.locationtech.jts.geom.GeometryFactory;
31  
32  /**
33   * A Jackson deserializer for a {@link Geometry}.
34   *
35   * @author Christian Bremer
36   */
37  public class JacksonGeometryDeserializer extends StdDeserializer<Geometry> {
38  
39    @Serial
40    private static final long serialVersionUID = 3L;
41  
42    /**
43     * The json to geometry converter.
44     */
45    private final JsonToGeometryConverter geometryConverter;
46  
47    /**
48     * Default constructor.
49     */
50    public JacksonGeometryDeserializer() {
51      this(new GeometryFactory());
52    }
53  
54    /**
55     * Constructs a deserializer that uses the specified geometry factory.
56     *
57     * @param geometryFactory the geometry factory
58     */
59    public JacksonGeometryDeserializer(GeometryFactory geometryFactory) {
60      super(Geometry.class);
61      GeometryFactory gf = isNull(geometryFactory) ? new GeoJsonGeometryFactory() : geometryFactory;
62      this.geometryConverter = new JsonToGeometryConverter(gf);
63    }
64  
65    @Override
66    public Geometry deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
67      Map<String, Object> map = jp.readValueAs(new MapTypeReference());
68      if (isNull(map) || map.isEmpty()) {
69        return null;
70      }
71      return geometryConverter.convert(map);
72    }
73  
74    private static class MapTypeReference extends TypeReference<Map<String, Object>> {
75  
76      private MapTypeReference() {
77      }
78    }
79  }