java - 从 json 文件获取字符串时为 Null

标签 java json

我使用简单的 json

这是我的代码:

    public static String getDetails() {
    String name = System.getProperty("user.name");
    JSONParser parser = new JSONParser();

    File dir = new File("C:\\Users\\" + name + "\\AppData\\Roaming\\.minecraft\\launcher_profiles.json");

    if (dir.exists()) {
        Object obj = null;
        try {
            obj = parser.parse(new FileReader("C:\\Users\\" + name + "\\AppData\\Roaming\\.minecraft\\launcher_profiles.json"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = (JSONObject) obj;
        String da = (String) jsonObject.get("username");

        try {
            return obj.toString() + "\n" + da;

        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        System.out.println("dir no exist");
    }
    return  null;
}

当我打印出来时,它返回 json 文件中的所有文本,并从字符串“da”返回 null 我不知道为什么,因为它不为 null,它存在于文件中?

JSON 文件:https://hastebin.com/sirefacado.json

最佳答案

要访问用户名,您必须使用完全限定路径。在你的情况下是:

String da = (String) ((JSONObject)((JSONObject)jsonObject.get("authenticationDatabase")).get("d46e53840f3f41a2b9e44e2d4d72ebeb")).get("username");

也就是说,因为您的用户名被封装在 JSON 文件的以下部分中:

authenticationDatabase: {
  d46e53840f3f41a2b9e44e2d4d72ebeb: {
    accessToken: "86ccdfsdfsdfsc2c38ec6012a1ccfsdfR",
    username: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="78080a110e190c1d0a381d15191114561b17" rel="noreferrer noopener nofollow">[email protected]</a>",
    profiles: {
      ad4fa7102fb7432cb4e07d471e348c77: {
        displayName: "hio"
      }
    }
  }
}

要通过 token 访问用户名,您必须通过身份验证数据库。可能存在多个 id,因此您必须迭代所有现有的 id 为此你可以这样做

JSONObject authDatabase = (JSONObject) jsonObject.get("authenticationDatabase");
for(Object id : authDatabase.keySet()) {
  JSONObject authEntry = (JSONObject) authDatabase.get(id);
  String username = (String) authDatabase.get("username");
  /* now do something with the username. 
     You can abort after you found the first username 
     and store it in the da object, or create a list
     of existing usernames, ... */
}

关于java - 从 json 文件获取字符串时为 Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49243595/

相关文章:

java - 从 JSON 获取数据

java - 尝试使用 Robolectric 测试 XML 解析时出错

java - 如何在java中检查远程Windows上的进程是否启动

json - Mongodb更新语句: How do i update the json object?

java - Spring Rest Post 服务发送 null 值作为变量

java - 如何在 Jackson json 库中执行 peek()?

java - "Data source name not found and no default driver"

java - 将 JScrollPane 添加到框架时出错?

java - 使用二叉堆构建哈夫曼树

javascript - NodeJS HTTP 请求 POST ERROR socket 挂断