如何将JAXB转换为JSON?

时间:2012-06-05 11:07:55

标签: java json web-services rest jaxb

我需要为返回JAXB对象的基于XML的Web服务创建Web服务前端。我的前端需要返回RESTful格式。有没有办法将其转换为JSON?我的班级路径中有 jackson-mapper-asl jackson-core-asl

作为一个简单的测试,我返回一个Book的bean,它以JSON的形式输出,但JAXB对象(交付时间表)保持XML格式。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class DSWLIClient {

    @Autowired
    private DeliveryScheduleWS wliService;
    private BookService bs;

    @RequestMapping(value = "/DSDetails/{ds-number}", method = RequestMethod.GET)
    public @ResponseBody
    DeliverySchedule getDSDetails(@PathVariable("ds-number") String dsNumber) {
        DeliveryScheduleResponse dsDetails = wliService.getDeliveryScheduleWSSoap().getDSDetails(dsNumber);
        DeliverySchedule deliverySchedule = dsDetails.getDeliverySchedule();
        return deliverySchedule;
    }


    @RequestMapping(value = "/BookDetails/{isbn-number}", method = RequestMethod.GET)
    public @ResponseBody
    Book getBookDetails(@PathVariable("isbn-number") String isbnNumber) {
        bs = new BookService();
        Book b = bs.getBookByIsbn(isbnNumber);
        System.out.println(b.getAuthor());
        return b;
    }


}

1 个答案:

答案 0 :(得分:1)

您能显示您的配置文件(XML或类)吗?

此外,我将假设您使用的是HttpMessageConverter(http://www.ibm.com/developerworks/web/library/wa-restful/)类,而不是ContentNegotiatingViewResolver。

这很简单,大部分时间都是因为我们忘记添加所需的配置“mvc:annotation-driven”

如果您使用内容协商视图,此示例很棒http://www.mkyong.com/spring-mvc/spring-3-mvc-contentnegotiatingviewresolver-example/