我读取了 JSON 并将数据存储到不同的对象中。我在名为 Geometry
的类中存储了一些坐标。该类如下所示:
public class Geometry {
private Object[] coordinates;
private String type;
public Object[] getCoordinates() {
return coordinates;
}
}
正如你所看到的,坐标
字段是一个Object
类的数组。
知道坐标
总是有2个位置(2个坐标)并且这些坐标的类型是double
,我怎样才能得到double
code> 坐标值?
更准确地说,我必须在以下方法中编写什么才能让系统显式返回两个坐标?
public double[] returnCoordinates() {
double[] coord;
coord[0] = //?
coord[1] = //?
return coord;
}
最佳答案
一种解决方案是在 Geometry 对象内存储 Cooperative 对象的数组,甚至是 Collection。如果您还没有使用Gson仔细研究一下,它会让生活变得非常轻松。
class Coordinate {
private final double x;
private final double y;
public Coordinate(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
}
public class Geometry {
private final Collection<Coordinate> coordinates;
private final String type;
public Geometry(Collection<Coordinate> coordinates, String type) {
this.coordinates = coordinates;
this.type = type;
}
public Collection<Coordinate> getCoordinates() {
return coordinates;
}
}
关于java - 如何获取存储在 Java 对象中的变量的已知值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60875818/