簡體   English   中英

我如何在json文件中獲取每個json元素並將它們放入數組中

[英]How do i get every json elemet in a json file and put them in an array

[
  {
    "origin": "12345",
    "destination": "2345",
    "time": 37,
    "days": "37",
    "people": "45"
  },
  {
    "origin": "34562",
    "destination": "12341",
    "time": 28,
    "days": "27",
    "people": "99"
  },
  {
    "origin": "84532",
    "destination": "35521",
    "time": 40,
    "days": "17",
    "people": "39"
  },
  {
    "origin": "12312",
    "destination": "75435",
    "time": 17,
    "days": "17",
    "people": "35"
  },
...
]

我想獲取json文件中的每個json對象,並將它們放入數組中。 所以我需要一個“原始”字符串數組,“目標”字符串數組,“時間” int數組,“天”字符串數組和一個“人”字符串數組。

我之所以這樣是因為'[',並嘗試了很多方法來獲取每個元素,但是我無法獲取json.file中的每個元素。

public static void main(String[] args) {
        // TODO Auto-generated method stub
        File file = new File(dirPath + "move.json");
        try {
            String content = new String(Files.readAllBytes(Paths.get(file.toURI())), "UTF-8");
            JSONObject json = new JSONObject(content.substring(4));

謝謝

基本上,您必須創建一個地圖,該地圖的鍵是JSON對象中的鍵。 並且在JSON數組中進行迭代時,您將每個鍵值附加到已經創建的映射中

public class App 
{
    public static void main( String[] args ) throws Exception
    {
        File file = new File("input.json");
        String content = new String(Files.readAllBytes(Paths.get(file.toURI())), "UTF-8");
        JSONArray array = new JSONArray(content); //parse your string data to JSON Array
        Map<String, List<Object>> map = new HashMap<>(); //create a HashMap having a key type as String and values as List of Object, 
        //since you are creating array for each key
        for(int i=0; i<array.length(); i++) //looping on all JSON Objects
        {
            JSONObject obj = array.getJSONObject(i);
            for (String key : obj.keySet()) { //looping on all keys in each JSON Object
                if(map.get(key) == null)
                    map.put(key, new ArrayList<Object>()); //initializing the list for the 1st use
                map.get(key).add(obj.get(key));//adding the value to the list of the corresponding key
            }
        }

        //Output:
        for (String key : map.keySet()) {
            System.out.println(key);
            System.out.println(map.get(key));
        }
    }
}

輸出將是:

origin
[12345, 34562, 84532, 12312]
destination
[2345, 12341, 35521, 75435]
days
[37, 27, 17, 17]
time
[37, 28, 40, 17]
people
[45, 99, 39, 35]

暫無
暫無

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

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