1 file9 days ago
2

package readJsonFile;

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
package readJsonFile; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class Main { public static void main(String[] args) { Object obj; try { obj = new JSONParser().parse(new FileReader("json\\employee.json")); JSONObject jsonObject = (JSONObject) obj; // đọc firstName và lastName String firstName = (String) jsonObject.get("firstName"); String lastName = (String) jsonObject.get("lastName"); System.out.println("firstName: " + firstName); System.out.println("lastName: " + lastName); // đọc age long age = (Long) jsonObject.get("age"); System.out.println("age:" + age); // đọc address JSONObject address = (JSONObject) jsonObject.get("address"); String streetAddress = (String) address.get("streetAddress"); String district = (String) address.get("district"); String city = (String) address.get("city"); String state = (String) address.get("state"); String postalCode = (String) address.get("postalCode"); System.out.println("streetAddress: " + streetAddress); System.out.println("district: "+ district); System.out.println("city: "+ city); System.out.println("state: "+ state); System.out.println("postalCode: "+ postalCode); // đọc phoneNumbers JSONArray PhoneNumberArr = (JSONArray) jsonObject.get("phoneNumbers"); PhoneNumberArr.forEach(phone -> { String type = (String) ((JSONObject)phone).get("type"); String number = (String) ((JSONObject)phone).get("number"); System.out.println("type: "+ number); System.out.println("type: "+ type); }); String sex = (String) jsonObject.get("sex"); System.out.println("sex: " + sex); Double salary = (Double) jsonObject.get("salary"); System.out.println("salary: " + salary); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } } }