我在 SpringMVC 应用程序中使用 MappingJacksonJsonView 从我的控制器呈现 JSON。我希望对象中的 ObjectId 呈现为 .toString ,但它会将 ObjectId 序列化为其部分。它在我的 Velocity/JSP 页面中运行良好:
Velocity:
$thing.id
Produces:
4f1d77bb3a13870ff0783c25
Json:
<script type="text/javascript">
$.ajax({
type: 'GET',
url: '/things/show/4f1d77bb3a13870ff0783c25',
dataType: 'json',
success : function(data) {
alert(data);
}
});
</script>
Produces:
thing: {id:{time:1327331259000, new:false, machine:974358287, timeSecond:1327331259, inc:-260555739},…}
id: {time:1327331259000, new:false, machine:974358287, timeSecond:1327331259, inc:-260555739}
inc: -260555739
machine: 974358287
new: false
time: 1327331259000
timeSecond: 1327331259
name: "Stack Overflow"
XML:
<script type="text/javascript">
$.ajax({
type: 'GET',
url: '/things/show/4f1d77bb3a13870ff0783c25',
dataType: 'xml',
success : function(data) {
alert(data);
}
});
</script> …
Run Code Online (Sandbox Code Playgroud) 有许多 问题涉及从转换ObjectId
到String
与杰克逊。所有答案都建议创建自己的JsonSerializer<ObjectId>
或ObjectId
使用@JsonSerialize(using = ToStringSerializer.class)
.
但是,我有一张有时包含的地图ObjectIds
,即:
class Whatever {
private Map<String, Object> parameters = new HashMap<>();
Whatever() {
parameters.put("tom", "Cat");
parameters.put("jerry", new ObjectId());
}
}
Run Code Online (Sandbox Code Playgroud)
我希望杰克逊将其转换为:
{
"parameters": {
"tom": "cat",
"jerry": "57076a6ed1c5d61930a238c5"
}
}
Run Code Online (Sandbox Code Playgroud)
但我得到:
{
"parameters": {
"tom": "cat",
"jerry": {
"date": 1460103790000,
"machineIdentifier": 13747670,
"processIdentifier": 6448,
"counter": 10631365,
"time": 1460103790000,
"timestamp": 1460103790,
"timeSecond": 1460103790
}
}
}
Run Code Online (Sandbox Code Playgroud)
我已经注册了转换(在 Spring 中)
public class …
Run Code Online (Sandbox Code Playgroud)