Reputation: 309
There is a List of Lists of Float values as Json, how is it possible to get 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]
. What is wrong with my code?
Upvotes: 1
Views: 3298
Reputation: 21125
azurefrog's answer is perfect for your question. 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. Here is a good Q/A describing the differences between the objects and primitives. 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):
final float[][] values = gson.fromJson(firstData, float[][].class);
...
Upvotes: 0
Reputation: 10945
You don't need to define your own wrapper class, you can just directly use a type token of List<List<Float>>
like so:
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
. Rather, it's a List
of a class that contains a List<Float>
.
Upvotes: 4