Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

53.6. GeoJson 反序列化

正常情况下是不需要做反序列化操作的。如花你想测试,打印一些信息可以这样做。

		
package cn.netkiller.api.config;

import java.io.IOException;

import org.springframework.data.mongodb.core.geo.GeoJsonPoint;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;

public class GeoJsonDeserializer extends JsonDeserializer<GeoJsonPoint> {

	@Override
	public GeoJsonPoint deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {

		final JsonNode tree = jsonParser.getCodec().readTree(jsonParser);
		final String type = tree.get("type").asText();
		final JsonNode coordsNode = tree.get("coordinates");

		System.out.println(tree.toString());
		System.out.println(type);
		System.out.println(coordsNode.toString());

		double x = 0;
		double y = 0;
		if ("Point".equalsIgnoreCase(type)) {
			x = coordsNode.get(0).asDouble();
			y = coordsNode.get(1).asDouble();
		} else {
			System.out.println(String.format("No logic present to deserialize %s ", tree.asText()));
		}

		final GeoJsonPoint point = new GeoJsonPoint(x, y);

		return point;
	}
}

		
		

使用 @JsonDeserialize 指定反序列化 Class

		
@Document
public class Address {
	@Id
	private String id;
	// @GeoSpatialIndexed
	@JsonDeserialize(using = GeoJsonDeserializer.class)
	private GeoJsonPoint location; // GPS 定位信息
}