java spring MappingJacksonJsonView不在mongodb ObjectId上做toString

sbz*_*oom 5 java spring json mongodb jackson

我在 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>
Produces:
    <com.place.model.Thing>
        <id>
            <__time>1327331259</__time>
            <__machine>974358287</__machine>
            <__inc>-260555739</__inc>
            <__new>false</__new>
        </id>
        <name>Stack Overflow</name>
    </com.place.model.Thing>
Run Code Online (Sandbox Code Playgroud)

有没有办法阻止 MappingJacksonJsonView 从 ObjectId 中获取那么多信息?我只想要 .toString() 方法,而不是所有细节。

谢谢。

添加 Spring 配置:

@Configuration
@EnableWebMvc
public class MyConfiguration {

    @Bean(name = "viewResolver")
    public ContentNegotiatingViewResolver viewResolver() {
        ContentNegotiatingViewResolver contentNegotiatingViewResolver = new ContentNegotiatingViewResolver();
        contentNegotiatingViewResolver.setOrder(1);
        contentNegotiatingViewResolver.setFavorPathExtension(true);
        contentNegotiatingViewResolver.setFavorParameter(true);
        contentNegotiatingViewResolver.setIgnoreAcceptHeader(false);
        Map<String, String> mediaTypes = new HashMap<String, String>();
        mediaTypes.put("json", "application/x-json");
        mediaTypes.put("json", "text/json");
        mediaTypes.put("json", "text/x-json");
        mediaTypes.put("json", "application/json");
        mediaTypes.put("xml", "text/xml");
        mediaTypes.put("xml", "application/xml");
        contentNegotiatingViewResolver.setMediaTypes(mediaTypes);
        List<View> defaultViews = new ArrayList<View>();
        defaultViews.add(xmlView());
        defaultViews.add(jsonView());
        contentNegotiatingViewResolver.setDefaultViews(defaultViews);
        return contentNegotiatingViewResolver;
    }

    @Bean(name = "xStreamMarshaller")
    public XStreamMarshaller xStreamMarshaller() {
        return new XStreamMarshaller();
    }

    @Bean(name = "xmlView")
    public MarshallingView xmlView() {
        MarshallingView marshallingView = new MarshallingView(xStreamMarshaller());
        marshallingView.setContentType("application/xml");
        return marshallingView;
    }

    @Bean(name = "jsonView")
    public MappingJacksonJsonView jsonView() {
        MappingJacksonJsonView mappingJacksonJsonView = new MappingJacksonJsonView();
        mappingJacksonJsonView.setContentType("application/json");
        return mappingJacksonJsonView;
    }
}
Run Code Online (Sandbox Code Playgroud)

还有我的控制器:

@Controller
@RequestMapping(value = { "/things" })
public class ThingController {

    @Autowired
    private ThingRepository thingRepository;

    @RequestMapping(value = { "/show/{thingId}" }, method = RequestMethod.GET)
    public String show(@PathVariable ObjectId thingId, Model model) {
        model.addAttribute("thing", thingRepository.findOne(thingId));
        return "things/show";
    }
}
Run Code Online (Sandbox Code Playgroud)

sbz*_*oom 1

之前的答案确实解决了问题,但它很丑陋,而且没有经过深思熟虑——这是一个实际解决问题的明确解决方法。

真正的问题是ObjectId反序列化为其组成部分。MappingJacksonJsonView看到ObjectId它是什么,一个物体,然后开始研究它。JSON 中看到的反序列化字段是构成ObjectId. 要停止此类对象的序列化/反序列化,您必须配置CustomObjectMapper扩展的ObjectMapper.

这里是CustomeObjectMapper

public class CustomObjectMapper extends ObjectMapper {

    public CustomObjectMapper() {
        CustomSerializerFactory sf = new CustomSerializerFactory();
        sf.addSpecificMapping(ObjectId.class, new ObjectIdSerializer());
        this.setSerializerFactory(sf);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是ObjectIdSerializer使用CustomObjectMapper的:

public class ObjectIdSerializer extends SerializerBase<ObjectId> {

    protected ObjectIdSerializer(Class<ObjectId> t) {
        super(t);
    }

    public ObjectIdSerializer() {
        this(ObjectId.class);
    }

    @Override
    public void serialize(ObjectId value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException {
        jgen.writeString(value.toString());
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是@Configuration带注释的类中需要更改的内容:

@Bean(name = "jsonView")
public MappingJacksonJsonView jsonView() {
    final MappingJacksonJsonView mappingJacksonJsonView = new MappingJacksonJsonView();
    mappingJacksonJsonView.setContentType("application/json");
    mappingJacksonJsonView.setObjectMapper(new CustomObjectMapper());
    return mappingJacksonJsonView;
}
Run Code Online (Sandbox Code Playgroud)

您基本上是在告诉杰克逊如何序列化/反序列化这个特定的对象。奇迹般有效。

  • 不需要自定义序列化器。只需使用 **ToStringSerializer** 即可。 (2认同)