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中文网其他相关文章!