Search code examples
javajsonmultidimensional-arrayjacksonprimitive

Jackson databind read json tri-dimensional array


I want to read a json Array and put it, if possible, into an int tri-dimensional array.

The data will look like this, I can change it's design to suit my needs as it is not done yet. The values are dumb but what is good to know is that (Caution mindf*ck ahead) I have to nest an unknown number of arrays containing integers, two times in an array that is repeated three times or less in the root node.

I.E. int[3 or less][2][unknown int] = val

I wrote the keys to improve readability, they may or may not be part of the actual json.

{
    demand : {
        0 : {
           0 :{
               0 :22,
               1 :32,
               2 :21
            },
            1 :{
               0 :2762,
               1 :352,
               2 :231
            }
        },
        1 :{
            0 :{
               0 :222,
               1 :232,
               2 :621
             },
             1 :{
               0 :272,
               1 :37762,
               2 :261 
             }
         }
     }
}

The point is that the keys and values are all integers and I would like to create an int [][][] with it. I think that the answer is in this doc : Jackson Full Databinding but I do not understand properly how it would work for my data.

I'm thinking about some ObjectMapper.readValue(json, new TypeReference>() { })` and will continue to look into this but I don't have much hope.

Thanks for any help!

Edit Here is the actual valid JSON

[  [   [  22, 32,  21   ],  [ 2762,  352, 231 ] ], [    [  222, 232,  621 ],  [ 272,  37762, 261]] ]

Solution

  • Serializing/Deserializing arrays with Jackson is the same as serializing anything else:

    public class App 
    {
        public static void main(String[] args) throws JsonProcessingException {
    
            int[][][] a = new int[2][3][2];
            a[0][2][0] = 3;
    
            ObjectMapper om = new ObjectMapper();
    
            // Serialize to JSON
            String json = om.writeValueAsString(a);
            System.out.println(json);
    
            // deserialize back from JSON
            a = om.readValue(json, int[][][].class);
            System.out.println(a[0][2][0]);
    
       }
    }
    

    output:

    [[[0,0],[0,0],[3,0]],[[0,0],[0,0],[0,0]]]
    3

    That said, unless you know it's always going to be a three dimensional array, you're be better served using Lists