Heim >Java >javaLernprogramm >JSON in Java
The format for data exchange, which is lightweight, based on text, independent of language, and easily read and written by both humans and machines, is JavaScript Object Notation, also called JSON in Java. This represents two types of structures called objects and arrays where an object is a collection of none or more than zero name and value pairs and is an unordered collection, and an ordered sequence of none or more than zero values is an array. The possible values can be numbers, strings, Booleans, null, objects, and arrays.
ADVERTISEMENT Popular Course in this category JAVA MASTERY - Specialization | 78 Course Series | 15 Mock TestsStart Your Free Software Development Course
Web development, programming languages, Software testing & others
Code:
{ "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" } ] }
Given below are the examples of JSON in Java:
Java program to demonstrate encoding of JavaScript Object Notation (JSON) in Java.
Code:
//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); } }
In the above example, a JSON object obje is created. Using the JSON object obje. The values like double, integer, Boolean, string, etc., are printed as output.
Output:
Java program to demonstrate the use of JSON object and JSON array.
Code:
//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); } } }
In the above example, a JSON object of the JSON parser par is created, then a string value is defined and assigned. A JSON array is created to obtain different specified elements in the string.
Output:
Java program to write JavaScript Object Notation data into a file with the name JSON.json using JavaScript Object Notation object and JavaScript Object Notation array.
Code:
//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(); } }
In the above example, a JSON object job is created. First name, last name, and age is written to the JSON.json file using the job object. A linked hash map is created to add the address details, which are then written to the file using the JSON job object. JSON array object is created to add the phone numbers, and the linked hash map is used to create different types of phone numbers; finally, the JSON job object is used to write these phone numbers to the file. Ultimately using a print writer, the contents are written to the file.
Output:
The output of the above program is when the file JSON.json is accessed to see the file’s contents.
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:
Das obige ist der detaillierte Inhalt vonJSON in Java. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!