【发布时间】:2019-07-21 15:07:57
【问题描述】:
我想转换一个 JSON 而不是包含这样的 Array 元素:
[{ "_id" : "01001", "city" : "AGAWAM", "loc" : [ -72.622739, 42.070206 ], "pop" : 15338, "state" : "MA" }
,
{ "_id" : "01002", "city" : "CUSHMAN", "loc" : [ -72.51564999999999, 42.377017 ], "pop" : 36963, "state" : "MA" }
,
{ "_id" : "01005", "city" : "BARRE", "loc" : [ -72.10835400000001, 42.409698 ], "pop" : 4546, "state" : "MA" }]
元素 loc 是一个数组,里面有两个元素。 我有以下代码将 JSON 转换为 Java 对象:
public ModelAndView listCities() throws IOException {
ModelAndView mav = new ModelAndView(ViewConstant.CITIES);
ObjectMapper mapper = new ObjectMapper();
Cities[] obj = mapper.readValue(new File("routeOfTheJSONFile"), Cities[].class);
mav.addObject("cities", obj);
return mav;
}
我的实体如下所示:
import java.util.Arrays;
public class Cities {
private String _id;
private String city;
private double[] loc;
private String pop;
private String state;
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public double[] getLoc() {
return loc;
}
public void setLoc(double[] loc) {
this.loc = loc;
}
public String getPop() {
return pop;
}
public void setPop(String pop) {
this.pop = pop;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
@Override
public String toString() {
return "Cities{" +
"_id='" + _id + '\'' +
", city='" + city + '\'' +
", loc=" + Arrays.toString(loc) +
", pop='" + pop + '\'' +
", state='" + state + '\'' +
'}';
}
}
HTML 是这样的:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" type="text/css" href="../css/bootstrap.min.css">
<title>Starbucks</title>
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<div class="col">
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>City</th>
<th>Location</th>
<th>Population</th>
<th>State</th>
</tr>
</thead>
<tbody>
<tr th:each="city : ${cities}">
<td th:text="${city._id}"></td>
<td th:text="${city.city}"></td>
<td th:text="${city.loc}"></td>
<td th:text="${city.pop}"></td>
<td th:text="${city.state}"></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<script src="../js/jquery-3.3.1.min.js"></script>
<script src="../js/popper.min.js"></script>
<script src="../js/bootstrap.min.js"></script>
</body>
</html>
但是当我在表格中显示信息时,loc 列是这样的:
[D@6481f9f9
[D@41e9a11f
[D@af30d01
我该如何解决这个问题?
【问题讨论】:
-
它不是“加密”的,它是 Arrays#toString 的结果。尝试在 loc 数组的每个元素上调用 toString。
-
Whups,您已经在您的
toString()中使用Arrays.toString(),现在我只是感到困惑...您确定您的toString()方法实际上是用于显示表格吗? -
这取决于您对
ModelAndView实例的用途。您是否在服务器端生成表并将HTML页面的一部分发送回客户端?或者您想通过RESTAPI返回JSON并在客户端处理响应? -
不要重新发明轮子,使用 Jackson 或 GSON。
-
@MichałZiober 是的,问题出在具有 col 属性的 Location 列上,但我不想将其更改为 Ajax,我只想让它在表格中正确显示。跨度>
标签: java json spring spring-boot spring-mvc