我如何在json文件中获取每个json元素并将它们放入数组中

时间:2019-08-23 12:46:04

标签: java arrays json

[
  {
    "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对象并将它们放在数组中。 所以我需要一个“原始”字符串数组,“目标”字符串数组,“时间”整数数组,“天”字符串数组和一个“人”字符串数组。

我之所以这样开始是因为'[',并尝试了很多方法来获取每个元素,但是我无法获取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));

谢谢

1 个答案:

答案 0 :(得分:0)

基本上,您必须创建一个映射,该映射的键是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]