簡體   English   中英

按特定順序獲取JSON數組的鍵和值

[英]Getting Keys and Values of a JSON Array in the specific order

我是Java的新手,我用它來教我的Lego NXT機器人以某種方式擺脫迷宮。 算法參數應該外包並加載到代碼中,這就是我使用JSON的原因。 我的JSON文件非常簡單(左手algorthm):

{"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;
            }
        }           
    }

我現在需要知道是否可以獲得密鑰字符串(我實際上使用了算法[i] .key)和值字符串(algorithm [i] .value)相同。

非常感謝您的幫助!

你可能應該更改你的JSON以便它被訂購,如下所示:

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

然后相應地修改Java。

我不熟悉JSON,但由於JSONObject由HashMap支持,您可以按照下面的相同順序將鍵和值放入數組中,

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++;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM