【问题标题】:Java JSONArray Object Returns HTML Format?Java JSONArray 对象返回 HTML 格式?
【发布时间】:2018-07-06 13:56:22
【问题描述】:

我正在使用 Java Spring,我正在尝试以 json 格式返回一个 JSON 对象。然而,我下面的控制器为 JSON 数据返回了一个有趣的 HTML 格式,见下文。 我希望控制器将数据返回为 JSON 格式的数据而不是 XML...

有什么想法吗? 谢谢, 皮特

返回数据:

    <JSONArray><item><date><date>11</date><hours>15</hours><seconds>52</seconds> 
   <month>11</month><nanos>0</nanos><timezoneOffset>300</timezoneOffset> 
   <year>117</year><minutes>32</minutes><time>1513024372000</time><day>1</day> 
   </date><exception></exception><level>DEBUG</level> 
   <logger>com.foo.bar.webapp.controller.ReconcileController</logger><id>91</id> 
   <message>filter was empty</message></item><item><date><date>11</date> 
   <hours>15</hours><seconds>52</seconds><month>11</month><nanos>0</nanos> 
   <timezoneOffset>300</timezoneOffset><year>117</year><minutes>32</minutes> 
   <time>1513024372000</time><day>1</day></date><exception></exception> 
   <level>DEBUG</level><logger>com.foo.bar.webapp.controller.ReconcileController
   </logger><id>92</id><message>returning labels as string</message> 
   </item><item><date><date>11</date><hours>15</hours><seconds>52</seconds> 
   <month>11</month><nanos>0</nanos><timezoneOffset>300</timezoneOffset> 
   <year>117</year><minutes>32</minutes><time>1513024372000</time><day>1</day> 
   </date><exception></exception><level>DEBUG</level> 
   <logger>com.foo.bar.webapp.controller.ReconcileController...

控制器方法:

@RequestMapping("/data*")
@Produces("application/json")
@ResponseBody
public JSONArray getData() {

    List<LogEntry> logs = logEntryManager.getLogsByDate( new Date() );

    JsonConfig config = new JsonConfig();
    config.addIgnoreFieldAnnotation(com.fasterxml.jackson.annotation.JsonIgnore.class);

    Log.trace("Get LogEntry Data Only");
    JSONArray jsonArray = JSONArray.fromObject( logs, config );

    return jsonArray;
}

【问题讨论】:

  • 请发布您的 pom.xml(如果它是 maven 项目)或项目中包含的库?
  • 另外,如果你将Accept header 设置为 `application/json' at rest 客户端(如 Postman),你会得到想要的结果吗?

标签: java json spring controller


【解决方案1】:
@RequestMapping(value = "data", method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON) // import javax.ws.rs.core.MediaType
public @ResponseBody JSONArray getData() {

    List<LogEntry> logs = logEntryManager.getLogsByDate( new Date() );

    JsonConfig config = new JsonConfig();
    config.addIgnoreFieldAnnotation(com.fasterxml.jackson.annotation.JsonIgnore.class);

    Log.trace("Get LogEntry Data Only");
    JSONArray jsonArray = JSONArray.fromObject( logs, config );

    return jsonArray;
}

忽略您的 @Produces 注释

试试这个。

【讨论】:

  • 这不起作用 :( 仍然返回 XML 样式数据。
  • 这行得通。我将 RequestMethod 更改为 GET 并且成功了!
猜你喜欢
  • 2015-11-08
  • 2013-07-19
  • 2018-05-11
  • 2021-12-18
  • 2018-08-01
  • 1970-01-01
  • 2013-02-19
  • 1970-01-01
  • 2017-07-31
相关资源
最近更新 更多