You need to enable JavaScript to run this app. Java实现JSON文件存储的用户登录时无法单独提取账号密码字段问题
优惠活动
大模型
产品
解决方案
定价
更多

Java实现JSON文件存储的用户登录时无法单独提取账号密码字段问题

解决方案

你当前使用的JSONArray是数组结构,无法直接通过字段名取值,需要先取出数组中对应的JSONObject用户对象,再通过字段名提取属性值,你使用的是json-simple库,具体可运行实现如下:

完整修改后的校验方法

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.json.simple.parser.ParseException;

public static void credentialCheck(String existingUsername, String sha256hexEntrdPaswrd){ 
        // 校验用户凭证有效性
        boolean validUser = false;
        JSONArray userArray = new JSONArray();
        Object ob = null;
        JSONParser jsonParser = new JSONParser();
        try {
            FileReader file = new FileReader("JSONUserLoginProject.json");
            ob = jsonParser.parse(file);
            userArray = (JSONArray) ob;
            file.close();
            
            // 遍历所有用户匹配用户名
            for (int i = 0; i < userArray.size(); i++) {
                JSONObject currentUser = (JSONObject) userArray.get(i);
                // 提取username和password_hash字段
                String storedUsername = (String) currentUser.get("username");
                String storedPwdHash = (String) currentUser.get("password_hash");
                
                // 匹配用户名后校验密码哈希
                if (storedUsername.equals(existingUsername)) {
                    if (storedPwdHash.equals(sha256hexEntrdPaswrd)) {
                        validUser = true;
                        System.out.println("凭证校验通过");
                    }
                    break;
                }
            }
            
            // 单独提取指定索引用户的字段示例
            // 取索引1的john用户信息
            JSONObject johnUser = (JSONObject) userArray.get(1);
            System.out.println(johnUser.get("username")); // 输出 john
            System.out.println(johnUser.get("password_hash")); // 输出 1fefaaaceda5a7e199e2c612ca6716d6da8065eed5a1a50979a309f27797e01f
            
        } 
        catch(FileNotFoundException e) {e.printStackTrace();}
        catch(IOException e) {e.printStackTrace();}
        catch(ParseException e) {e.printStackTrace();}
        catch(Exception e) {e.printStackTrace();}
}

注意事项

  • JSON字段名大小写敏感,你的JSON文件中字段为username、password_hash,不要写错大小写
  • 取值时需要强制类型转换为String,避免后续字符串比对报错

内容的提问来源于stack exchange,提问作者TinusLorvalds

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 04:27:02