Convert ArrayList<JsonArray> to float[][] in Java

梦想的初衷 提交于 2019-12-12 06:37:07

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!