如何从spring REST Controller获取geoJSON? [英] How to get geoJSON from spring REST Controller?
问题描述
我正在使用java(Spring-4.1.5 + Hibernate-4.3.8)和OpenLayers开发GIS应用程序。对于这个项目,我使用 GeoTools-13RC
, HibernateSptial-4.3
, jts-1.13
和 jackson-2.5
。
在这个项目中,我在客户端和服务器中有一个层,我在一个类中保存了这个层的功能。我在下面定义了这个类:
I am developing a GIS application with java(Spring-4.1.5 + Hibernate-4.3.8) and OpenLayers. For this project I use GeoTools-13RC
, HibernateSptial-4.3
, jts-1.13
and jackson-2.5
.
In this project, I have a layer in client side and in server, I save the features of this layer in a class. I defined the class below:
@Entity
@Table(name="MyPoint")
public class MyPoint
{
@id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long Id;
@Column
private String name;
@Type(type = "org.hibernate.spatial.GeometryType")
@Column(name = "the_geom")
private Point geometry;
/*
*
Getter and Setter
*
*/
}
在启动应用程序时,我需要在客户端初始化该层。为此,我需要从服务器端返回一个json字符串到该层的客户端。我不想使用 ST_AsGeoJson
或其他匹配。 我使用Spring REST控制器返回我的实体。
In start up of application, I need to init the layer in client side. for this, I need return from server side a json string to client for this layer. I don't want to use ST_AsGeoJson
or other matches. I use Spring REST controller for returning my Entity.
我该怎么做?
推荐答案
返回对客户的回复
您需要创建一个资源来公开你的客户。关于这个主题有一些很好的 Spring文档,以及几种不同的方法做到这一点,但基本上是这样的:
Returning a Response to the Client
You will need to create a resource to expose to your client. There is some good Spring documentation on this topic, and a couple of different ways to do it, but essentially something like this:
@Component
@Path("/my_points")
public class MyPoints {
private PointService pointService;
@GET
@Path("{pointId}")
public Response getPoint(@PathParam("pointId") String pointId) {
return Response.ok(pointService.getById(pointId)).build();
}
}
构建JSON
您应该使用Jackson构建您的JSON。如果您构建Spring资源,那么在构造响应时,Jackson可能会默认使用。为了让您了解如何手动将对象转换为JSON:
Building JSON
You should use Jackson to build your JSON. If you build a Spring resource then Jackson will likely be used by default when constructing a response. To give you an idea of how to translate an object to JSON manually:
@Test
public void serializingAnObjectToJson() throws Exception {
// Create a mapper that translates objects to json/xml/etc using Jackson.
ObjectMapper om = new ObjectMapper();
MyPoint point = new MyPoint(223l, "Superman");
// Creates a JSON representation of the object
String json = om.writeValueAsString(point);
// Create a JAX-RS response with the JSON as the body
Response response = Response.ok(json).build();
}
这篇关于如何从spring REST Controller获取geoJSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!