我需要覆盖/修复第三方类(谷歌地图类)的序列化机制,以便我可以从磁盘上的文件中编码对象。我见过several examples我正在尝试做的事情,但似乎都不起作用。
问题阶层:
public class LatLng implements UrlValue {
public double lat;
public double lng;
public LatLng(double lat, double lng) {
this.lat = lat;
this.lng = lng;
}
}
我的混音
public abstract class LatLnMixIn {
@JsonCreator
public LatLnMixIn(@JsonProperty("lat") Double lat, @JsonProperty("lng ")Double lng) {}
}
我的使用情况
ObjectMapper mapper = new ObjectMapper().addMixIn(LatLng.class, LatLnMixIn.class);
InputStream mockStream = this.getClass().getResourceAsStream("/mz-to-nordstrom-rack-snoq.json");
DirectionsResult mockResult = mapper.readValue(mockStream, DirectionsResult.class);
要编码(marshal)的 json 片段:
"start_location" : {
"lat" : 47.5985728,
"lng" : -122.3315845
},
我的错误(有/没有mixin)
com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class com.google.maps.model.LatLng]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)
有人看出我哪里出了问题吗?
最佳答案
Mixins 使用匹配的构造函数和方法签名。你的目标类构造函数看起来像
public LatLng(double lat, double lng)
而你的 mixin 构造函数定义为
public LatLnMixIn(Double lat, Double lng)
Jackson 将 double
和 Double
视为不同的类型,因此在目标类中找不到匹配的构造函数。
只需更改构造函数以使用双
参数即可。
在此特定示例中不需要 @JsonCreator
注释。
关于java - Jackson Mixin + 创建者不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41230107/