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 java.util.Map;
22  import org.bremersee.geojson.GeoJsonGeometryFactory;
23  import org.locationtech.jts.geom.Geometry;
24  import org.locationtech.jts.geom.GeometryFactory;
25  import tools.jackson.core.JsonParser;
26  import tools.jackson.core.type.TypeReference;
27  import tools.jackson.databind.DeserializationContext;
28  import tools.jackson.databind.deser.std.StdDeserializer;
29  
30  /**
31   * A Jackson deserializer for a {@link Geometry}.
32   *
33   * @author Christian Bremer
34   */
35  public class JacksonGeometryDeserializer extends StdDeserializer<Geometry> {
36  
37    /**
38     * The json to geometry converter.
39     */
40    private final JsonToGeometryConverter geometryConverter;
41  
42    /**
43     * Default constructor.
44     */
45    public JacksonGeometryDeserializer() {
46      this(new GeometryFactory());
47    }
48  
49    /**
50     * Constructs a deserializer that uses the specified geometry factory.
51     *
52     * @param geometryFactory the geometry factory
53     */
54    public JacksonGeometryDeserializer(GeometryFactory geometryFactory) {
55      super(Geometry.class);
56      GeometryFactory gf = isNull(geometryFactory) ? new GeoJsonGeometryFactory() : geometryFactory;
57      this.geometryConverter = new JsonToGeometryConverter(gf);
58    }
59  
60    @Override
61    public Geometry deserialize(JsonParser jp, DeserializationContext ctxt) {
62      Map<String, Object> map = jp.readValueAs(new MapTypeReference());
63      if (isNull(map) || map.isEmpty()) {
64        return null;
65      }
66      return geometryConverter.convert(map);
67    }
68  
69    private static class MapTypeReference extends TypeReference<Map<String, Object>> {
70  
71      private MapTypeReference() {
72      }
73    }
74  }