所以我使用GSON解析了一个非常大的JSON文件。 我正在解析它的类是这样的结构:
我要做的是将双打(在HashSet中,在Geometry类中)舍入到4个小数点。因此,当双打被添加到HashSet时,我想要将它们四舍五入。
public class Contours {
public String name = null;
public String type = null;
ArrayList<Features> features = null;
class Features {
public String type = null;
public Geometry geometry = null;
public Properties properties = null;
}
class Geometry {
public String type = null;
HashSet<double[]> coordinates = null;
}
class Properties {
public String CONTOUR = null;
public int OBJECTID;
public String LAYER = null;
public double ELEVATION;
}
}
该文件非常大,有412,064行,大小为27.5mb。这样做需要很长时间。
注意:每次运行此应用程序时都会进行此解析,因此速度是必要的。
由于
答案 0 :(得分:1)
您可以注册TypeAdapter
来修改值,因为它们已被阅读:
public class GsonDoubleAdapterTest {
public static void main(String[] args) {
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Double.class, new DoubleAdapter());
Gson gson = builder.create();
Foo foo = gson.fromJson("{\"baz\": 0.123456}", Foo.class);
System.out.println(foo);
}
}
/**
* A type adapter that rounds doubles during read.
*/
class DoubleAdapter extends TypeAdapter<Double> {
@Override
public void write(JsonWriter out, Double value) throws IOException {
out.value(value);
}
@Override
public Double read(JsonReader in) throws IOException {
return new BigDecimal(in.nextDouble()).setScale(4, RoundingMode.HALF_UP).doubleValue();
}
}
class Foo {
private Double baz;
public Double getBaz() {
return baz;
}
public void setBaz(Double baz) {
this.baz = baz;
}
@Override
public String toString() {
return "Foo[baz=" + baz + ']';
}
}