转换ArrayList< JsonArray>在Java中浮动[] [] [英] Convert ArrayList<JsonArray> to float[][] in Java

查看:114
本文介绍了转换ArrayList< JsonArray>在Java中浮动[] []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Gson将 ArrayList< JsonArray> 转换为 float [] []


$ b $ 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.2287287200,0.0007858753,0.742472785,0.019066211,0.050337251,0.00062063418],
...]

人们说我应该用两次扫描每个项目并进行转换,但不知道是否有更自动化的方式。

fromJson 取第二个参数来描述你的数据。它可以是 Class code> 类型






Class example



 字符串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); (float [] a:r){
for(float f:a){
System.out.println(f);






$ b

类型示例



 键入myType = new TypeToken< ArrayList< ArrayList< Float> ;>>(){} .getType(); 
列表<列表<浮点>> r = gson.fromJson(json,myType); (浮动f:a){
System.out.println(f);
for(List< Float> a:r)
}
}


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.

解决方案

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

这篇关于转换ArrayList&lt; JsonArray&gt;在Java中浮动[] []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆