Skip to content Skip to sidebar Skip to footer

Convert Arraylist To Float[][] In Java

What is best and fastest way to convert an ArrayList to float[][] using Gson? The ArrayList is a 2D array of long with this sample format: [ [ -0

Solution 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);
    }
}

Post a Comment for "Convert Arraylist To Float[][] In Java"