问题
What is best and fastest way to convert an ArrayList<JsonArray> to float[][] using Gson?
The ArrayList <JsonArray> is a 2D array of long with this sample format:
[ [ -0.0028871582, -0.0017856462, 0.0078000603, 0.003144495, 0.0042561297, -0.026877755, 0.019066211, 0.050337251, -0.00062063418],
[ -0.6545645087, 0.7474752828, 1.8797838739, 0.287287200, 0.0007858753, -0.742472785, 0.019066211, 0.050337251, -0.00062063418],
... ]
People say I should scan each item with two go and do the conversion but do not know if there is a more automated means for this.
回答1:
As @njzk2 mentioned fromJson takes a second parameter describing your data. It can be a Class or a Type.
Class example
String json = "[\n" +
" [ -0.0028871582, -0.0017856462, 0.0078000603 ],\n" +
" [ -0.6545645087, 0.7474752828, 1.8797838739 ]\n" +
"]\n";
Gson gson = new GsonBuilder().create();
float[][] r = gson.fromJson(json, float[][].class);
for (float[] a: r) {
for (float f : a) {
System.out.println(f);
}
}
Type example
Type myType = new TypeToken<ArrayList<ArrayList<Float>>>() {}.getType();
List<List<Float>> r = gson.fromJson(json, myType);
for (List<Float> a: r) {
for (Float f: a) {
System.out.println(f);
}
}
来源:https://stackoverflow.com/questions/37887814/convert-arraylistjsonarray-to-float-in-java