Obtain keys and values ​​from a JSON array in the specific order

advertisements

I'm very new to Java, I'm using it to teach my Lego NXT Robot some ways out of a labyrinth. The algorithm parameters shall be outsourced and loaded in the code, so thats why I use JSON. MY JSON file is pretty simple (lefthand algorthm):

{"algorithm":
    {
      "onGapLeft": "moveLeft",
      "onGapFront": "moveForward",
      "onGapRight": "moveRight",
      "default": "moveBackward"
    }
}

It's very important that this file is read in it's order. I.e. if you change Left and Right the algorithm would become a Right Hand Algorithm. This is the Java Code so far, I hope you understand what I'm trying to do. BTW: I'm using JSON.simple!

private static void loadAlgorithm() throws InterruptedException {

        JSONParser parser = new JSONParser();

            Object obj = parser.parse(new FileReader("lefthand.json"));
            JSONObject jsonObject = (JSONObject) obj;
            JSONArray algorithm = (JSONArray) jsonObject.get("algorithm");
            int length = algorithm.size();

        for(int i = 0; i < length; i++)
        {
            switch (algorithm[i].key)
            {
                 case "onGapLeft" :  leftPos = i; break;
                 case "onGapFront": frontPos = i; break;
                 case "onGapRight": rightPos = i; break;
                 default: break;
            }

            switch (algorithm[i].value)
            {
                 case "moveLeft"    : directionAlgorithm[i] = direction.Left;     break;
                 case "moveFront"   : directionAlgorithm[i] = direction.Forward;  break;
                 case "moveRight"   : directionAlgorithm[i] = direction.Right;    break;
                 case "moveBackward": directionAlgorithm[3] = direction.Backward; break;
                 default: break;
            }
        }
    }

I'll need to know now wether it is possible to get the key string (where I used algorithm[i].key actually) and the same for the value string (algorithm[i].value).

Thank you very much for your help!


You should probably change your JSON so that it is ordered, something like this:

{"algorithm":
    [
        { "key": "onGapLeft", "value" : "moveLeft" },
        { "key": "onGapFront", "value" : "moveForward" },
        { "key": "onGapRight", "value" : "moveRight" },
        { "key": "default", "value" : "moveBackward" }
    ]
}

And then modify your Java accordingly.