Heim >Java >javaLernprogramm >JSON in Java

JSON in Java

WBOY
WBOYOriginal
2024-08-30 16:02:12574Durchsuche

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 Tests

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Working with JSON in Java

  • Consider the below example for representing an object in JSON to describe a person.
  • First name and last name takes the values of string in the object; age takes the value of numbers in the object; address takes the values of stings and numbers to represent the address of the person in the object; the phone number takes the value of arrays in the object.

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"
}
]
}
  • The processing of JavaScript Object Notation (JSON) in Java is done through the Java application programming interface using JavaScript Object Notation, i.e., JSON.simple, The JavaScript Object Notation JSON.simple is a library in Java that allows parsing JavaScript Object Notation, generating JavaScript Object Notation, transforming JavaScript Object Notation, querying JavaScript Object Notation, etc.
  • In order to work with JavaScript Object Notation simple library, json-simple-1.1.jar must be downloaded and put in the CLASS PATH before we compile and run the JavaScript Object Notation programming examples.
  • The JavaScript Object Notation object and structures of array use the object modules provided by JavaScript Object Notation simple application programming interface.
  • These JavaScript Object Notation structures use the types JSON object and JSON array to be represented as object models. The JSON object provides a map view to access the collection of none or more than zero name and value pairs from the model. It is an unordered collection, and the JSON array provides a List view to access the ordered sequence of none or more than zero values in an array from the model.

Examples of JSON in Java

Given below are the examples of JSON in Java:

Example #1

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:

JSON in Java

Example #2

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:

JSON in Java

Example #3

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. JSON in Java

Example #4

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:

JSON in Java

Das obige ist der detaillierte Inhalt vonJSON in Java. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:Java-VerzeichnisseNächster Artikel:Java-Verzeichnisse