JavaScript 物件表示法(JavaScript Object Notation),在 Java 中也稱為 JSON,是一種輕量級、基於文字、獨立於語言、易於人類和機器讀寫的資料交換格式。這表示兩種類型的結構,稱為物件和數組,其中物件是沒有或超過零的名稱和值對的集合,並且是無序集合,而沒有或超過零值的有序序列是數組。可能的值可以是數字、字串、布林值、null、物件和陣列。
廣告 該類別中的熱門課程 JAVA 掌握 - 專業化 | 78 課程系列 | 15 次模擬測驗開始您的免費軟體開發課程
網頁開發、程式語言、軟體測試及其他
代碼:
{ "fName": "Shobha", "lName": "Shivakumar", "age1": 28, "address1": { "streetAdd": "4, Ibbani street", "city1": "Bangalore", "state1": "Karnataka", "pinCode": 560064 }, "phNumbers": [ { "type1": "home1", "no": "9738128018" }, { "type2": "fax1", "no1": "6366182095" } ] }
下面給出了 Java 中 JSON 的範例:
Java 程序,用於示範 Java 中 JavaScript 物件表示法 (JSON) 的編碼。
代碼:
//Importing JSON simple library import org.json.simple.JSONObject; //Creating a public class public class JsonEncode { //Calling the main method public static void main(String[] args) { //Creating an object of JSON class JSONObject obje = new JSONObject(); //Entering the values using the created object obje.put("bal", new Double(100.22)); obje.put("number", new Integer(200)); obje.put("check_vvip", new Boolean(true)); obje.put("name1", "sean"); //Printing the values through the created object System.out.print(obje); } }
在上面的範例中,建立了一個 JSON 物件 obje。使用 JSON 物件 object.雙精確度、整數、布林值、字串等值將作為輸出列印。
輸出:
示範 JSON 物件和 JSON 陣列使用的 Java 程式。
代碼:
//importing JSON simple libraries import org.json.simple.JSONObject; import org.json.simple.JSONArray; import org.json.simple.parser.ParseException; import org.json.simple.parser.JSONParser; //creating a public class public class JsonDecode{ //calling the main method public static void main(String[] args) { //creating an object of JSONparser JSONParser par = new JSONParser(); //defining and assigning value to a string String str = "[2,{\"3\":{\"4\":{\"5\":{\"6\":[7,{\"8\":9}]}}}}]"; try{ Object objc = par.parse(str); //creating a JSON array JSONArray array = (JSONArray)objc; System.out.println("The array's second element is"); System.out.println(array.get(1)); System.out.println(); //creating a JSON object JSONObject objc2 = (JSONObject)array.get(1); System.out.println("Field \"2\""); System.out.println(objc2.get("2")); str = "{}"; objc = par.parse(str); System.out.println(objc); str = "[7,]"; objc = par.parse(str); System.out.println(objc); str = "[7,,2]"; objc = par.parse(str); System.out.println(objc); }catch(ParseException pr) { System.out.println("The elements position is: " + pr.getPosition()); System.out.println(pr); } } }
在上面的範例中,建立了 JSON 解析器 par 的 JSON 對象,然後定義並指派了一個字串值。建立一個 JSON 陣列來取得字串中不同的指定元素。
輸出:
使用 JavaScript 物件表示法物件和 JavaScript 物件表示法陣列將 JavaScript 物件表示法資料寫入名為 JSON.json 的檔案的 Java 程式。
代碼:
//importing java simple libraries and JSON libraries import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.LinkedHashMap; import java.util.Map; import org.json.simple.JSONArray; import org.json.simple.JSONObject; public class JSONWrite { public static void main(String[] args) throws FileNotFoundException { // Json object is created JSONObject job = new JSONObject(); // Adding data using the created object job.put("fName", "Shobha"); job.put("lName", "Shivakumar"); job.put("age1", 28); // LinkedHashMap is created for address data Map m1 = new LinkedHashMap(4); m1.put("streetAdd", "4, Ibbani Street"); m1.put("city1", "Bangalore"); m1.put("state1", "Karnataka"); m1.put("pinCode", 560064); // adding address to the created JSON object job.put("address1", m1); // JSONArray is created to add the phone numbers JSONArray jab = new JSONArray(); m1 = new LinkedHashMap(2); m1.put("type1", "home1"); m1.put("no", "9738128018"); // adding map to list jab.add(m1); m1 = new LinkedHashMap(2); m1.put("type2", "fax1"); m1.put("no1", "6366182095"); // map is added to the list jab.add(m1); // adding phone numbers to the created JSON object job.put("phoneNos", jab); // the JSON data is written into the file PrintWriter pwt = new PrintWriter("JSON.json"); pwt.write(job.toJSONString()); pwt.flush(); pwt.close(); } }
在上面的範例中,建立了一個 JSON 物件作業。使用作業物件將名字、姓氏和年齡寫入 JSON.json 檔案。建立連結哈希映射以添加地址詳細信息,然後使用 JSON 作業對象將其寫入文件。建立 JSON 陣列物件來新增電話號碼,並使用連結的雜湊映射來建立不同類型的電話號碼;最後,使用 JSON 作業物件將這些電話號碼寫入檔案。最終使用列印編寫器將內容寫入文件。
輸出:
上述程式的輸出是存取檔案 JSON.json 以查看文件內容時的結果。
Note: Since JSON is an unordered collection of name or value pairs, there is no order preserved in the output shown below.Java program to read the contents of the file JSON. JSON demonstrates the use of JavaScript Object Notation object parser, JavaScript Object Notation object, and JavaScript Object Notation object array.
Code:
//importing JSON simple libraries import java.io.FileReader; import java.util.Iterator; import java.util.Map; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.*; public class JSONRead { public static void main(String[] args) throws Exception { // The file JSON.json is parsed Object objc = new JSONParser().parse(new FileReader("JSON.json")); // objc is convereted to JSON object JSONObject job = (JSONObject) objc; // obtaining the fname and lname String fName = (String) job.get("fName"); String lName = (String) job.get("lName"); System.out.println(fName); System.out.println(lName); // age is obtained long age1 = (long) job.get("age1"); System.out.println(age1); // address is obtained Map address1 = ((Map)job.get("address1")); // iterating through the address Iterator<Map.Entry> itr = address.entrySet().iterator(); while (itr.hasNext()) { Map.Entry pair1 = itr1.next(); System.out.println(pair1.getKey() + " : " + pair1.getValue()); } // phone numbers are obtained JSONArray jab = (JSONArray) job.get("phoneNos"); // iterating phoneNumbers Iterator itr1 = jab.iterator(); while (itr1.hasNext()) { itr = ((Map) itr1.next()).entrySet().iterator(); while (itr.hasNext()) { Map.Entry pair1 = itr.next(); System.out.println(pair1.getKey() + " : " + pair1.getValue()); } } } }
In the above example, the file JSON.json is parsed by creating an object objc which is then converted to a JSON object job. First name, last name, age, address, and phone numbers are read from the JSON.json file through iterations and printed as the output.
Output:
The output of the above program after reading the contents from the JSON.json file is shown in the snapshot below:
以上是Java 中的 JSON的詳細內容。更多資訊請關注PHP中文網其他相關文章!