0

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!

6
  • 1
    I don't think it solves your problem completely, but you've misinterpreted "algorithm" as a JSONArray. It's actually a JSONObject, meaning just like how you got "algorithm" from the root object, you can get "onGapLeft"/"onGapFront" values from the algorithm object. Arrays have their values declared sequentially with [] brackets and commas, and do not have string labels (ex.: ["moveLeft", "moveRight"] Commented Sep 5, 2013 at 20:30
  • Yeah, there's no "array" in that JSON. And the order of entries in an "object" (map/dictionary) are "not defined" -- even if they arrive in one order the code that parses the JSON can legitimately rearrange them. Commented Sep 5, 2013 at 20:52
  • (One wonders why you have key names for the individual values, if they will always be in a given order. It would make more sense to just have an array of [moveLeft, moveForward, moveRight, moveBackward], if that's what you want. Or make the key names be "firstMove", "secondMove", "thirdMove", "fourthMove".) Commented Sep 5, 2013 at 20:56
  • (See json.org for the JSON spec. It takes only 5-10 minutes to learn.) Commented Sep 5, 2013 at 20:57
  • Thanks everyone! So if I change the JSON like zigdawgydawg stated below, it'll be sorted then? @HotLicks: This would be a solution, but we want to have it more custamizable, tehrefore we've added this two value solution! :) Commented Sep 5, 2013 at 21:08

2 Answers 2

2

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.

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

5 Comments

Thanks! Does this solve the problem Katana314 stated, that my JSON file is not an array at the moment? :) And is it then possible to iterate thorugh this via "algorithm[i].key"? i.e. algorithm[0].key would be OnGapLeft? :)
Yes...it does solve the problem that @Katana314 mentioned. The [...] in JSON is a proper (and ordered) array. As you are iterating through the algorithm JSONArray, get the JSONObject at each index with JSONObject obj2 = (JSONObject) algorithm.get(i); and then to get that object's key obj2.get("key");. I hope that helps.
Okay! Now I have just one problem with the initialising. The line: Object obj = parser.parse(new FileReader("lefthand.json")); has an error saying: "Unhandled exception type ParseException" Any suggestions? (As I said: I'm completely new to Java and Eclipse and sometimes I don't get what it wants to tell me :)
You'll either need to wrap that line in a try/catch block or explicitly specify that the loadAlgorithm method throws ParseException. Here is more information about the two options: here
Thank you very much! This helped, the program compiled, everythings fine. Big problem now: That damn Lego Robot doesn't understand simpleJSON. I now have to work myself through a non library but java file json lib.. I hope that's not too complicated. I think I'm going to cry a little bit now. Thanks anyways ;)
0

I am not familiar with JSON , but Since JSONObject is backed by a HashMap, you may be able to get the keys and values into a array in the same order like below,

Map<K, V> map = new HashMap<K, V>();
K[] keys = new K[map.size()];
V[] values = new V[map.size()];
int index = 0;
for (Map.Entry<K, V> mapEntry : map.entrySet()) {
    keys[index] = mapEntry.getKey();
    values[index] = mapEntry.getValue();
    index++;
}

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.