1

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?

3
  • use gson did you? Commented Apr 10, 2017 at 19:14
  • is that a valid JSON in your string?? Commented Apr 10, 2017 at 19:19
  • @jackjay yes it is Commented Apr 10, 2017 at 19:23

2 Answers 2

4

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>.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.