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.serialization;
18  
19  import com.fasterxml.jackson.core.JsonGenerator;
20  import com.fasterxml.jackson.databind.SerializerProvider;
21  import com.fasterxml.jackson.databind.ser.std.StdSerializer;
22  import java.io.IOException;
23  import java.io.Serial;
24  import org.locationtech.jts.geom.Geometry;
25  
26  /**
27   * A Jackson serializer for a {@link Geometry}.
28   *
29   * @author Christian Bremer
30   */
31  public class JacksonGeometrySerializer extends StdSerializer<Geometry> {
32  
33    @Serial
34    private static final long serialVersionUID = 3L;
35  
36    /**
37     * The geometry to json converter.
38     */
39    private final GeometryToJsonConverter converter;
40  
41    /**
42     * Instantiates a new Jackson geometry serializer.
43     */
44    public JacksonGeometrySerializer() {
45      this(false, false);
46    }
47  
48    /**
49     * Instantiates a new Jackson geometry serializer.
50     *
51     * @param withBoundingBox the with bounding box
52     * @param useBigDecimal the use big decimal
53     */
54    public JacksonGeometrySerializer(boolean withBoundingBox, boolean useBigDecimal) {
55      super(Geometry.class, false);
56      this.converter = new GeometryToJsonConverter(withBoundingBox, useBigDecimal);
57    }
58  
59    @Override
60    public void serialize(
61        Geometry value,
62        JsonGenerator jgen,
63        SerializerProvider provider)
64        throws IOException {
65  
66      if (value == null) {
67        jgen.writeNull();
68      } else {
69        jgen.writeObject(converter.convert(value));
70      }
71    }
72  
73  }