[英]Reading JSON file using java
我的問題是我不知道我已經閱讀了 JSON 數組leave_applicants的第一個 JSON 對象。 這是我需要使用java找到的。
{
"leave_applicants":[
{
"applicant_name" : "Jhon",
"supervisor_name" : "Mark",
"org" : "UNDP",
"index_no" : 1,
"leave_details": {
"leave_type" : "annual",
"from" : "12-07-2018",
"to" : "15-07-2018"
}
},
{
"applicant_name" : "Ravi",
"supervisor_name" : "Mark",
"org" : "UNDP",
"index_no" : 2,
"leave_details": {
"leave_type" : "sick_leave_cert",
"from" : "20-07-2018",
"to" : "25-07-2018"
}
}
]
}
使用一個簡單的Json解析庫,我喜歡GSON( https://github.com/google/gson )
假設 JSON 位於存儲在您計算機上的文本文件中。 請參閱以下代碼,在 for 循環的每次迭代結束時,將出現 JSON 數組的第一個 JSON 對象的結尾(如您所願)。
import java.io.FileReader;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class ReadingJSONFromFile {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader(
"Path/To/JSON/File/json_file.txt"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray leaveApplicants = (JSONArray) jsonObject.get("leave_applicants");
for(Object applicants: leaveApplicants) {
JSONObject app = (JSONJObject)applicants;
String name = (String) app.get("applicant_name"); // Get the applicant name
// You can get the other keys of the object similarly and display them as you want
// This will be the end of the first object of the JSON Array
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.