nonamerz nonamerz - 6 months ago 22
JSON Question

Parse JSON with Gson. Difficult JSON structure without keys

How can I create the correct object for the following structure?

JSON without any keys and with arrays in arrays in arrays:

{
"1": [
[
[1.111, 2.222]
[1.111, 2.222]
...
],
[
[1.111, 2.222]
...
]
],
"2": [
[
[1.111, 2.222]
...
],
[
[1.111, 2.222]
...
]
],
...
}

Answer

I won't give you the code solution, but I will explain your format. The JSON format is explained in detail here.

You have

{
"1": [
      [
         [1.111, 2.222]
         [1.111, 2.222]
         ...
      ],
      [
         [1.111, 2.222]
         ...
      ]
   ],...

Your root element is a JSON object. It contains a number of pairs. Each pair ("1": ...) has a value that is a JSON array [...]. Each of these JSON arrays contains element which are JSON arrays [...]. These JSON arrays finally contain elements which are JSON number primitives [12.34].

So your JSON has the following levels (number between parenthesis is conceptual nested level)

Object (0)
   name -> Array (1) of Arrays (2)
            -> Array (2) of Arrays (3)
                -> Array (3) of number primitives

This could be mapped to a Map<String, List<List<List<Double>>>> as you have three nested levels of arrays.

If you have a custom class, that could work too, but it will be hard to map the root pair names as you can't have dynamic field names in Java classes. That's why I suggest a Map above.

Alternatively, you could just parse the JSON as a com.google.gson.JsonObject and traverse the object structure to get the element you want.