簡體   English   中英

轉換ArrayList <JsonArray> 在Java中浮動[] []

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

使用Gson將ArrayList<JsonArray>轉換為float[][]最佳最快方法是什么?

ArrayList <JsonArray>是帶有以下示例格式的long二維數組:

[ [ -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],
... ]

人們說我應該兩次掃描每個項目並執行轉換,但是不知道是否有更自動化的方法。

正如@ n​​jzk2在fromJson中提到的, fromJson采用了第二個參數來描述您的數據。 它可以是ClassType


Class例子

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示例

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM