如何使用GSON过滤JSON中的数据

edqdpe6u  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(219)

我有这个JSON文件:

{"status":"success","data":[{"id":1,"employee_name":"Tiger Nixon","employee_salary":320800,"employee_age":61,"profile_image":""},{"id":2,"employee_name":"Garrett Winters","employee_salary":170750,"employee_age":63,"profile_image":""},{"id":3,"employee_name":"Ashton Cox","employee_salary":86000,"employee_age":66,"profile_image":""}

为了阅读“状态”,我的代码看起来像这样,它工作正常

JsonObject json = new Gson().fromJson(responseText, JsonObject.class);
System.out.println(json.get("status"));

问:我如何才能得到第二个雇员的名字(加勒特Winters)?我已经试过了,但它不工作:-(

System.out.println(json.get("data.employee_name(2)"));
System.out.println(json.get("data[2].employee_name"));
System.out.println(json.get("data/employee_name(2)"));
System.out.println(json.get("data/employee_name[2]"));
cxfofazt

cxfofazt1#

为了得到你想要的东西,你需要链接方法。

json.getAsJsonArray("data").get(2).getAsJsonObject().get("employee_name")

相关问题