【发布时间】:2015-08-08 13:56:21
【问题描述】:
我正在尝试替换一个旧的 ASP 页面,该页面返回填充一个浮点图表的 JSON。 (http://www.flotcharts.org/)
我的问题是这样的,
旧的 ASP 页面返回这个 JSON:
{"xaxis":{"ticks":[[100,"Location1"],[200,"Location2"],[300,"Location3"]]}}
如您所见,“ticks”包含一个包含 2 个成员的数组列表。每个数组的第一个成员是一个数字,第二个是一个字符串。
我能用 SpringMVC/SpringBoot 得到的最接近的是:
{"xaxis":{"ticks":[["100","Location1"],["200","Location2"],["300","Location3"]]}}
您会注意到这些数字实际上是字符串。
这是我正在使用的控制器:
@Controller
public class GraphWebController {
@RequestMapping(value = "/getXAxisData", method = RequestMethod.GET)
public @ResponseBody Map<String, XAxisData> getXAxisData(Model model) {
String[] location1 = new String[]{"100", "Location1"};
String[] location2 = new String[]{"200", "Location2"};
String[] location3 = new String[]{"300", "Location3"};
List<String[]> xAxisLocations = new ArrayList<String[]>();
xAxisLocations.add(location1);
xAxisLocations.add(location2);
xAxisLocations.add(location3);
XAxisData xaxis = new XAxisData(xAxisLocations);
Map<String, XAxisData> xAxisData = new HashMap<String, XAxisData>();
xAxisData.put("xaxis", xaxis);
return xAxisData;
}
}
public class XAxisData {
private List<String[]> ticks;
public XAxisData(List<String[]> ticks) {
this.ticks = ticks;
}
public List<String[]> getTicks() {
return ticks;
}
public void setTicks(List<String[]> ticks) {
this.ticks = ticks;
}
}
我尝试将 String 数组更改为 Object 数组,并将引用的数字更改为实际整数,但随后出现以下错误,即 Object 无法转换为 String。
<html><body><h1>Whitelabel Error Page</h1><p>This application has no explicit mapping for /error, so you are seeing this as a fallback.</p><div id='created'>Tue May 26 14:28:55 EDT 2015</div><div>There was an unexpected error (type=Internal Server Error, status=500).</div><div>Could not write JSON: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String; (through reference chain: java.util.HashMap["xaxis"]->springmvc.graph.XAxisData["ticks"]->java.util.ArrayList[0]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String; (through reference chain: java.util.HashMap["xaxis"]->springmvc.graph.XAxisData["ticks"]->java.util.ArrayList[0])</div></body></html>
如何获得与旧 ASP 页面完全相同的输出?
在这一点上,我对 hacky 解决方案持相当开放的态度。不过,hacky 越少越好。谢谢!
【问题讨论】:
-
你能显示
XAxisData吗? -
另外,请发布您所做的确切更改及其完整的堆栈跟踪。
-
另外,还有,你是使用 Jackson(哪个版本?)还是 Gson 来序列化 JSON?
-
用 XAxisData 和完整的堆栈跟踪更新了问题。在堆栈跟踪中,我看到它引用了 Jackson。我会尝试找出哪个版本。有可能是 SpringBoot 自带的默认版本之类的。
-
从包名可以看出,
fasterxml是版本2。
标签: java json spring-mvc spring-boot flot