0

我对 Java 很陌生,我正在用它来教我的 Lego NXT 机器人走出迷宫的一些方法。算法参数应外包并加载到代码中,这就是我使用 JSON 的原因。我的 JSON 文件非常简单(左手算法):

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

按顺序读取此文件非常重要。即如果你改变左右算法将成为右手算法。这是迄今为止的Java代码,我希望你明白我想要做什么。顺便说一句:我正在使用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;
            }
        }           
    }

我现在需要知道是否可以获得密钥字符串(我实际上使用了 algorithm[i].key)和值字符串(algorithm[i].value)。

非常感谢您的帮助!

4

2 回答 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.

于 2013-09-05T20:31:20.950 回答
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++;
}
于 2013-09-05T20:46:51.077 回答