首页 > 解决方案 > java - 如何从java中的json对象循环读取信息?

问题描述

我在下面有以下 JSON 数组,我想创建一个 for 循环,从数组中的每个对象中提取每个用户名、传递、错误。如何在 java 中做到这一点。

[
  {
    "username": "",
    "password": "",
    "expectedError": "Enter your user ID."
  },
  {
    "username": "exa",
    "password": "",
    "expectedError": "Enter your password."
  }
]

这是我用来读取 json 文件的方法

public static JSONArray parseJsonFile () {
    JSONParser jsonParser = new JSONParser();
    try (FileReader reader = new FileReader("src/main/resources/list.json")){
        Object obj = jsonParser.parse(reader);
        JSONArray list = (JSONArray) obj;
        System.out.println(list);
        return list;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

这是我希望使用提取的数据的地方

public void loginWith(String username, String password) {
    usernameInput.clear();
    usernameInput.sendKeys(username); // want to extract the value of username in json file and send it herejaza
    passwordInput.clear();
    passwordInput.sendKeys(password);
    signInButton.click();
}

标签: javaseleniummavenfor-loop

解决方案


使用 jacksonAPI 很容易。往下看,看看 Baeldung 网站上的教程:

import com.fasterxml.jackson.databind.ObjectMapper;
...
   ObjectMapper mapper = new ObjectMapper();

   List<User> listUsers = objectMapper.readValue(stringFromFile, new TypeReference<List<User>>(){});


...

教程 Baeldung


推荐阅读