2 回答
TA贡献1828条经验 获得超6个赞
获取值时可以转换为字符串。像这样更改您的代码,看看它是否有帮助。
JsonObject object = (JsonObject) new JsonParser().parse(new FileReader("C:\\MyData\\response.json"));
JsonArray issues = (JsonArray) object.get("issues");
JsonObject issues0 = (JsonObject) issues.get(0);
String issue_key = (String) issues0.get("key");//<---here
System.out.println("Value of key is -> " + issue_key);
更新
如果您想要所有值,只需将其放在“for”中:
JsonObject object = (JsonObject) new JsonParser().parse(new FileReader("C:\\MyData\\response.json"));
JsonArray issues = (JsonArray) object.get("issues");
for(int i=0; i<issues.size(); i++){
JsonObject issue = (JsonObject) issues.get(i);
String issue_key = (String) issue.get("key");
System.out.println("Value of key" + Integer.toString(i + 1) + " is -> " + issue_key);
}
更新 2
“更新”和“创建”的数据不在“问题”内,它们在“字段”内才能访问它们,您需要从“字段”中获取它们。您必须逐级进入内部才能访问变量:
JsonObject object = (JsonObject) new JsonParser().parse(new FileReader("C:\\MyData\\response.json"));
JsonArray issues = (JsonArray) object.get("issues");
for(int i=0; i<issues.size(); i++){
JsonObject issue = (JsonObject) issues.get(i);
String issue_key = (String) issue.get("key");
JsonObject fields = (JsonObject) issues.get("fields");
JsonObject project = (JsonObject) issues.get("project");
String project_name = (String) project.get("key");
String fields_updated = (String) fields.get("updated");
String fields_created = (String) fields.get("created");
System.out.println("Value of key" + Integer.toString(i + 1) + " is -> " + issue_key);
}
TA贡献1844条经验 获得超8个赞
您收到一个错误,因为您将 a 投射JsonPrimitive到JsonObject. 所以而不是使用
JsonObject issues0data = (JsonObject) issues0.get("key");
你应该做
String issues0data = issues0.get("key").getAsString();
System.out.println("Value of key is -> " + issues0data);
在这里,调用getAsString()将调用JsonPrimitive.getAsString()方法。如果原语是boolean/number/string并将其转换为string.
添加回答
举报