【问题标题】:Returning ResponseEntity with List of an Object返回带有对象列表的 ResponseEntity
【发布时间】:2020-03-28 08:06:19
【问题描述】:

我有下面的函数,我试图用我的对象列表返回 ResponseEntity。我不知道我错过了什么。

    @RequestMapping(method = RequestMethod.GET, path = "/test")
    public ResponseEntity<List<Book>> test(@RequestParam("param1") String param1) {
        return new ResponseEntity<List<Book>>(this.service.searchOnParam1(param1), HttpStatus.OK);   
    }

我收到以下错误。我该如何克服这个问题?

WARN 37968 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver:已解决 [org.springframework.web.HttpMediaTypeNotAcceptableException:找不到可接受的表示]

图书课。

public class Book implements Serializable, Message
{

    Logger log = LogManager.getLogger(this.getClass());
    private long id;
    public long getId() {
        return this.id;
    }
    public void setId(long id) {
        this.id = id;
    }
    @MsgField(id = "COUNT")
    @JsonProperty("COUNT")
    private String  itemCount;
    @MsgField(id = "name")
    @JsonProperty("name")
    private String  name;
    @MsgField(id = "author")
    @JsonProperty("author")
    private String  author;
    @MsgField(id = "price")
    @JsonProperty("price")
    private String  price;

    public String getPriceFormatted(Locale locale){
        String returnValue = "0";
        try {
            final NumberFormat formatter = NumberFormat.getInstance(locale);
            formatter.setMaximumFractionDigits((int) 2);
            formatter.setMinimumFractionDigits((int) 2);
            formatter.setMinimumIntegerDigits(1);
            formatter.setRoundingMode(RoundingMode.HALF_DOWN);
            returnValue = formatter.format(price);
        } catch (NumberFormatException ex) {
            log.catching(ex);
        }
        return returnValue;        
    }

}

【问题讨论】:

  • 你不会错过你方法上的@Produces注解吗?
  • 请分享Book
  • 我曾尝试使用@Produces 返回 JSON,但这并没有帮助。你能建议我具体添加什么吗?

标签: java spring elasticsearch resthighlevelclient


【解决方案1】:

在实现 WebMVCConfigAdapter 的类中添加以下代码对我有用。

    @Override
    public void configureContentNegotiation(final ContentNegotiationConfigurer configurer)
    {
        configurer.ignoreAcceptHeader(true).defaultContentType(MediaType.APPLICATION_JSON_UTF8);
    }

对于我的应用程序,我总是只返回 JSON 数据。

【讨论】:

    【解决方案2】:

    将公共 getter 和 setter 以及公共构造函数添加到您的 Book 类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-18
      • 1970-01-01
      • 1970-01-01
      • 2018-01-11
      • 1970-01-01
      • 1970-01-01
      • 2014-10-13
      相关资源
      最近更新 更多