[英]Java Json to List of Lists
There is a List of Lists of Float values as Json, how is it possible to get List<List<Float>>
? 有一个Float值列表作为Json,如何获得List<List<Float>>
?
I tried something like: 我尝试过类似的东西:
class MyLine{
List<Float> values;
}
String firstData = "[[0.11492168, -0.30645782, 9.835381], [0.12449849, -0.29688102, 9.844957]]"
Gson gson = new Gson();
List<MyLine> firstList = gson.fromJson(firstData, new TypeToken<List<MyLine>>(){}.getType());
but I have an error Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 3 path $[0]
. 但我有一个错误Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 3 path $[0]
。 What is wrong with my code? 我的代码出了什么问题?
You don't need to define your own wrapper class, you can just directly use a type token of List<List<Float>>
like so: 您不需要定义自己的包装类,您可以直接使用List<List<Float>>
的类型标记,如下所示:
String firstData = "[[0.11492168, -0.30645782, 9.835381], [0.12449849, -0.29688102, 9.844957]]";
Gson gson = new Gson();
List<List<Float>> firstList = gson.fromJson(firstData, new TypeToken<List<List<Float>>>() {}.getType());
System.out.println(firstList);
// prints [[0.11492168, -0.30645782, 9.835381], [0.12449849, -0.29688102, 9.844957]]
A List<MyLine>
isn't actually a List<List<Float>>
unless MyLine
itself is a List
. 除非MyLine
本身是List
否则List<MyLine>
实际上不是List<List<Float>>
。 Rather, it's a List
of a class that contains a List<Float>
. 相反,它是一个List
, 其中包含一个一类List<Float>
。
azurefrog's answer is perfect for your question. azurefrog的答案非常适合您的问题。 You might also consider switching to another target deserialization type. 您还可以考虑切换到另一个目标反序列化类型。 The rationale: List<List<Float>>
is actually a list of lists of float wrappers where every wrapper holds a float value in your JVM heap separated, whilst float[][]
is an array of arrays of primitive floats where each float value does not require a wrapper box for a single float value in the heap (you can consider an array of primitives a sequence of values with plain memory layout) thus saving memory from more "aggressive" consumption. 基本原理: List<List<Float>>
实际上是一个浮动包装列表的列表,其中每个包装器在JVM堆中保存一个浮点值,而float[][]
是一个基本浮点数组的数组,其中每个浮点值对于堆中的单个浮点值,不需要包装盒(您可以将基元数组视为具有普通存储器布局的一系列值),从而节省内存,使其更加“积极”消耗。 Here is a good Q/A describing the differences between the objects and primitives. 这是一个很好的Q / A,描述了对象和基元之间的差异。 Sure, you won't see a significant difference for tiny arrays, but in case you would like to try it out, you don't even need a type token (because arrays, unlike generics, allow .class
notation): 当然,你不会看到微小数组的显着差异,但是如果你想尝试它,你甚至不需要类型标记(因为数组,不像泛型,允许.class
表示法):
final float[][] values = gson.fromJson(firstData, float[][].class);
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.