HttpMediaTypeNotAcceptableException XML ResponseEntity <list <>&gt; </list <>

时间:2014-09-16 16:45:11

标签: java xml json rest spring-mvc

我正在开发一个主要返回JSON的API,但如果客户端更喜欢使用XML,我也希望它返回XML。

我的控制器包含在下面。

我可以为http://127.0.0.1:8080/gender/1

返回JSON和XML

但是http://127.0.0.1:8080/gender/1仅使用JSON,XML返回HttpMediaTypeNotAcceptableException:找不到可接受的表示。

这是因为我正在尝试序列化List&lt;&gt;到XML?解决方案是什么?

package net.jkratz.bloodpressure.api.controller;

import net.jkratz.bloodpressure.api.model.Gender;
import net.jkratz.bloodpressure.api.repository.GenderRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import java.util.List;

@RestController
@RequestMapping(value = "/gender", produces = {"application/json","application/xml"})
public class GenderController {

    @Inject
    GenderRepository genderRepository;

    private Logger logger = LoggerFactory.getLogger(getClass());

    @RequestMapping(value = {"","/"}, method = RequestMethod.GET)
    public ResponseEntity<List<Gender>> getGenders(@RequestHeader("Accept") String acceptHeader) {
        logger.info("Serving resource for Accept header: {}", acceptHeader);
        List<Gender> genders = genderRepository.findAll();
        return new ResponseEntity<>(genders, HttpStatus.OK);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public ResponseEntity<Gender> getGender(@PathVariable("id") Integer id, @RequestHeader("Accept") String acceptHeader) {
        logger.info("Serving resource for Accept header: {}", acceptHeader);
        return new ResponseEntity<>(genderRepository.findOne(id), HttpStatus.OK);
    }
}

0 个答案:

没有答案