Search code examples
javajsonspring-bootgeometryjson-deserialization

How to deserialize / serialize type Geometry in spring boot?


I have an entity with attributes of type MultiPolygon and Point; so I'm making a get request but this is returning a SerializationException.

I researched it and saw that I have to put some notes, create a configuration class and put the corresponding dependency in pom.xml. Follow as I did below:

Entity:

package com.zxventures.model;

@Entity
@Table(name = "pdv")
public class PDV implements Serializable {

private static final long serialVersionUID = 1L;

 @Column(name="coverage_area")
 @JsonSerialize(using = GeometrySerializer.class)
 @JsonDeserialize(contentUsing = GeometryDeserializer.class)
 private MultiPolygon coverageArea;

 @Column(name="address")
 @JsonSerialize(using = GeometrySerializer.class)
 @JsonDeserialize(contentUsing = GeometryDeserializer.class)
 private Point address;
}

Config class:

package com.zxventures.config;

@Configuration
public class JacksonConfig {

 @Bean
 public JtsModule jtsModule() {
  return new JtsModule();
 }
}

pom.xml:

<dependency>
<groupId>com.bedatadriven</groupId>
<artifactId>jackson-datatype-jts</artifactId>
<version>2.4</version>
</dependency>

The exception occurs:

could not deserialize; nested exception is 
org.hibernate.type.SerializationException: could not deserialize

I think I'm missing some code but I can not detect it; I think I put all the code I saw in similar questions.


Solution

  • You're using Spatial data types, so need to include below dependency to work

    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-spatial</artifactId>
    </dependency>
    

    And change dialect accordingly e.g. org.hibernate.spatial.dialect.mysql.MySQL56InnoDBSpatialDialect

    See Spatial data types