我正在尋找使用org.json.simple庫解析以下數組並遇到困難。可能有人請看看我的JSON文件和代碼,並建議我在做什麼錯使用java解析和排序JSON數據
{
"Company": [
{
"Department": "Engineering",
"Employee": [
{
"EmpName": "Jack",
"EmpCode": "8",
"Type": "Permanent"
}, {
"EmpName": "John",
"EmpCode": "45",
"Type": "Permanent"
}, {
"EmpName": "Ron",
"EmpCode": "9",
"Type": "Contract"
}, {
"EmpName": "Jin",
"EmpCode": "6",
"Type": "Permanent"
}, {
"EmpName": "Jill",
"EmpCode": "",
"Type": "Retired"
}, {
"EmpName": "Sam",
"EmpCode": "89",
"Type": "Permanent"
}, {
"EmpName": "Jonathan",
"EmpCode": "66",
"Type": "Permanent"
}, {
"EmpName": "Craig",
"EmpCode": "",
"Type": "Ex-Employee"
}, {
"EmpName": "Son Hui",
"EmpCode": "4",
"Type": "Permanent"
}, {
"EmpName": "Joshua",
"EmpCode": "12",
"Type": "Contract"
}, {
"EmpName": "Tulip",
"EmpCode": "70",
"Type": "Contract"
}
]
}, {
"Department": "IT",
"Employee": [
{
"EmpName": "Nico",
"EmpCode": "50",
"Type": "Resigned"
}, {
"EmpName": "Phil",
"EmpCode": "103",
"Type": "Resigned"
}
]
}
]
}
注意幾個EmpCode領域也是空白。我應該如何處理它們。另外,我需要能夠在顯示數據時重新排列數據,我的意思是我需要根據EmpCode或Type對數據進行排序。
我寫的分析上面的JSON的代碼如下提到:
package amazontesting;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
public class json {
private static final String filePath = /emp.json";
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader(filePath));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("Department");
//String suites = (String) jsonObject.get("Company");
JSONArray slideContent = (JSONArray) jsonObject.get("Department");
Iterator i = slideContent.iterator();
while (i.hasNext()) {
System.out.println(i.next());
String title = (String) jsonObject.get("Employee");
System.out.println(title);
}
}
catch (FileNotFoundException e)
{}
catch(IOException e)
{}
catch(ParseException e)
{}
}
}
「建議我做錯了什麼」對於SO來說並不合適。請準確描述你遇到的問題,你已經做了什麼來診斷問題,然後構建一個[最小測試用例](http://stackoverflow.com/help/mcve)。 –
此外,代碼中引用的JSON聽起來不像發佈的JSON。 – johnnyaug
@OliverCharlesworth對不起,關於不正確的JSON引用,我已經更新了這些。我是處理JSON的新手,所以我在互聯網上閱讀並嘗試使用示例代碼。一些帖子提到我應該創建一個基於json的類,然後在主類中調用它,而一些人提到上面的代碼會做到這一點。我試圖運行這個代碼,部門打印空。 – BountyHunter