java - 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();
}
解决方案
使用 jacksonAPI 很容易。往下看,看看 Baeldung 网站上的教程:
import com.fasterxml.jackson.databind.ObjectMapper;
...
ObjectMapper mapper = new ObjectMapper();
List<User> listUsers = objectMapper.readValue(stringFromFile, new TypeReference<List<User>>(){});
...
推荐阅读
- jquery - 为什么 Jquery text() 方法在遍历 html 标签数组时返回错误
- makefile - 如何使用这个 makefile 生成我的抽象树?为什么我在 1 行只看到一个错误?
- python - 正则表达式从字符串中拆分正/负浮点/整数
- html - 如何在 HTML 中实现这种图像布局
- c++ - 在 C++ 中想出解决循环引用的问题
- javascript - 关于太阳/背景渲染的屏幕空间坐标问题
- java - JTable 需要信息行
- html - 如何将 dd 和 dt 元素设置在同一行,dt 右对齐和 dd 左对齐?
- cryptography - 如何在智能合约中计算配对
- python - 如何在列表中组合排序参数?