我有一个servlet,它将一个ArrayList传递给一个接收它的jsp页面,并将它放在一个数组中,但如果我将它们存储在这样的数组中,我就无法访问Loc中的参数:
var locations = new Array();
<c:forEach items="${photosName}" var="photo" varStatus="loop">
locations["${loop.index}"] = "${photo}";
</c:forEach>
变量照片包含我希望存储在locations数组中的纬度,经度和准确度等属性。但是,如果我像这样存储它们,我怎么能在代码的其他部分访问它们。
我想做的例子:
locations[i].latitude
locations[i].longitude
locations[i].accuracy
欢迎任何帮助:)
现在试过这个:
var locations = new Array();
<c:forEach items="${photosName}" var="photo" varStatus="loop">
locations["${loop.index}"] = JSON.stringify("${photo}");
</c:forEach>
alert("latitude: "+locations[0].latitude+ " longitude: "+locations[0].longitude);
它打印纬度:未定义经度:未定义。我需要为json.stringify导入一些东西吗?
jsp中的Photo对象由此类表示:
@Entity
public class Loc implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private long id;
private double latitude;
private double longitude;
private long time;
private double accuracy;
private int processed;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public double getLatitude() {
return this.latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return this.longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public long getTime() {
return this.time;
}
public void setTime(long time) {
this.time = time;
}
@Override
public String toString() {
return "latitude: " + latitude + " longitude: " + longitude + "time: "
+ time;
}
public double getAccuracy() {
return accuracy;
}
public void setAccuracy(double accuracy) {
this.accuracy = accuracy;
}
public int getProcessed() {
return processed;
}
public void setProcessed(int processed) {
this.processed = processed;
}
}
答案 0 :(得分:0)
试试locations["${loop.index}"] = {JSON.stringify("${photo}")};
。然后,您可以在编写时访问属性:
locations[i].latitude
locations[i].longitude
locations[i].accuracy
注意: photo是JSONObject的字符串表示形式。像这样:
JSONObject jsonPhoto = gson.toJson(photoObj) //photoObj is instance of your java photo object class
String photo = jsonPhoto.toString();
要将对象转换为json对象,可以使用GSON库。这是一个很好的教程link。
如果您有Java phtoObjects
列表,您可以在servlet中执行以下操作:
<%@ page import="com.google.gson.Gson" %>
<%GSON gson = new Gson();%>
var photoArray = JSON.stringify(<%=gson.toJson(phtoObjects).toString()%>);