How to write json objects into the file using java language?
Java read json file
The JSON is one of the broadly utilized information exchange designs and
is a lightweight and language free.
The json.simple is a lightweight
JSON handling library that can be utilized to peruse and compose JSON records
and it tends to be utilized to encode or disentangle JSON message and
completely consistent with JSON determination.
To peruse a JSON record, we
really want to download the json-simple.jar document and set the way to execute
it.
//code
import java.io.*;
import java.util.*;
import org.json.simple.*;
import org.json.simple.parser.*;
public class Example1 {
public static
void main(String[] args) {
JsonFile
parser1 = new JsonFile();
try {
Object
obj1 = parser.parse(new FileReader1("/Bhoomika/Victus/Desktop/course.json"));
jsonObject
= (JsonObject)obj1;
String
name1 = (String)jsonObject.get("Name of the student");
String
course1 = (String)jsonObject.get("Course obtained ");
JsonArray
subjects = (JsonArray)jsonObject.get("total Subjects");
System.out.println("Name of the student: " + name1);
System.out.println("Course obtained: " + course1);
System.out.println("total Subjects:");
Iterator1= subjects.iterator();
while
(iterator1.hasNext()) {
System.out.println(iterator1.next());
}
}
catch(Exception e) {
e.printStackTrace()
}
}
}
How to write json objects into the file using java
language?
The JSON is one of the broadly utilized information exchange designs and
is a lightweight and language free.
The json.simple is a lightweight
JSON handling library that can be utilized to peruse and compose JSON records
and it tends to be utilized to encode or disentangle JSON message and
completely consistent with JSON determination.
To peruse a JSON record, we
really want to download the json-simple.jar document and set the way to execute
it.
//code
import java.io.*;
import java.util.*;
import org.json.simple.*;
import org.json.simple.parser.*;
public class Example2 {
public static
void main(String[] args) throws IOException {
JsonObject
obj1 = new JsonObject();
Obj1.put("Name of the student", "Bhoomika");
Obj1.put("Course obtained by the student", "MBA");
JsonArray
subject = new JsonArray();
subject.add("Subj1: DAA");
subject.add("Subj2: OOPS");
subject.add("Subj3: DSA);
obj1.put("Subjects:", subject);
try{
(FileWriter
record1 = new FileWriter("/Bhoomika/Victus/Desktop/course11.json")) {
file.write(obj1.toJSONString());
System.out.println("Json object will be in touch with the file when
needed");
System.out.println("JSON Object1: " + obj1);
}
}
}
Reading json file:
//code
import java.io.*;
import java.util.*;
import org.json.simple.*;
import org.json.simple.parser.*;
public class Example3 {
public static
void main(String[] args) {
JsonParser
parser1 = new JsonParser();
try {
Object
obj2 = parser1.parse(new
FileReader1("/Bhoomika/Victus/Desktop/course11.json"));
jsonObject1 = (JSONObject)obj2;
String
name = (String)jsonObject1.get("Name of the student");
String
course = (String)jsonObject.get("Course obtained");
JsonArray
subjects = (JsonArray)jsonObject1.get("Subjects allotted");
System.out.println("Name of the student: " + name);
System.out.println("Course obtained by the student: " +
course);
System.out.println("Subject:");
Iterator1 = subject.iterator();
while
(iterator1.hasNext()) {
System.out.println(iterator1.next());
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
Json simple features:
·
Full consistence with JSON detail (RFC4627).
·
Upholds encode, interpret/parse and get away from
JSON.
·
Simple to use by reusing Map and List interfaces.
·
Upholds streaming result of JSON text.
·
High execution.
·
No dependency on outside libraries
Write json file:
To compose JSON test into the record, we will be working with chiefly
two classes:
1.
JSONArray: To compose information in json exhibits.
Utilize its add() technique to add objects of type JSONObject.
2.
JSONObject: To compose json objects. Utilize it's
put() technique to populate fields.
//code
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class WritingJSONExample1
{
@SuppressWarnings("unchecked")
public
static void main( String[] args )
{
//First
Employ
JSONObject employDetails1 = new JSONObject();
employDetails1.put("firstName of the employ",
"koushik");
employDetails1.put("lastName of the employ",
"Yadav");
employDetails1.put("website name",
"howtosolveinjava.com");
JSONObject employeeObject = new JSONObject();
employeeObject.put("employee", employeeDetails);
//Second
Employ
JSONObject employDetails11 = new JSONObject();
employeeDetails11.put("firstName of the employ", "Bhoomika");
employeeDetails11.put("lastName of the employ", "Reddy");
employeeDetails11.put("website
name", "javatpoint.com");
JSONObject employObject22 = new JSONObject();
employeeObject22.put("employ", employDetails22);
//Add
workers to list
JSONArray employList = new JSONArray();
employList.add(employObject);
employList.add(employObject22);
//Compose JSON document
try(FileWriter
f1 = new FileWriter("employ.json")) {
//We
can compose any JSONArray or JSONObject occurrence to the record
F1.write(employList.toJSONString());
F1.flush();
} get
(IOException e) {
e.printStackTrace();
}
}
}
Converting json file to string:
we can undoubtedly change over JSON records to strings. Changing over a
JSON document into a string is finished by perusing bytes of information of
that record.
To change over JSON records to string, we utilize the nio (non-hindering
I/O) package
(collection of Java programming language APIs that proposition
highlights for I/O activities).
Suppose the Demo.json file contains following data
{
"Name of the person": "Daniel",
"Mobile
Number": 8956795433,
"Boolean
value": tr,ue
"Pets": ["Dogs", "cats"],
"Address": {
"Long-lasting location": "AMERICA",
"current Address" : "INDIA"
}
}
We now use the below mentioned steps to convert json file into string
·
Import every one of the expected classes like Files,
Paths, and Scanner.
·
Take input from the client for the area and name.
·
Make convertFileIntoString()
·
In the convertFileIntoString() strategy, we utilize
the get() technique for the Paths class to get the document information.
·
We utilize the readAllBytes() strategy for the Files
class to peruse bytes information of the JSON documents as a string.
·
We store the returned consequence of the
readAllBytes()and get()methods into a variable and return it to the principal()
technique.
·
In the primary() strategy, we basically print the
returned consequence of the convertFileIntoString()
//code
// import required classes and bundles
// we use classes of nio bundle to peruse bytes
information of the JSON document
importjava.nio.file.Files;
importjava.nio.file.Paths;
importjava.util.Scanner;
// make ReadFileAsString class to change over json
document into string
public class ReadFileArrayString1 {
// primary()
technique start
public static void main(String[] args) throws
Exception {
//handle special case
// pronounce
fileName, area, and record variable that will store the client entered document
name, area, and document information as a string, individually
String
fileName, document, area;
// make
scanner class object
Scanner sc1
= new Scanner(System.in);
System.out.println("Enter the name of the
document which you need to change over or access as string: ");
// take
input from client and instate filName variable
fileName1 = sc1.nextLine();
System.out.print("Enter the location of the
"+fileName1+" document: ");
// take
input from client and introduce area variable
area = sc1.nextLine();
// close scanner class obj
Sc1.close();
// call
convertFileIntoString() strategy that will return the record information as
string. We store the returned information into document variable
Record1 =
convertFileIntoString(location+"\\"+fileName1);
// print
the outcome, i.e., JSON information in type of string
System.out.println(filename);
}
// make
convertFileIntoString() technique to change over JSON record into string
public static String convertFileIntoString(String
file)throws Exception
{
// proclaim
a variable wherein we store the JSON information as a string and return it to
the principal() technique
String
result1;
// instate
result variable
// we
utilize the get() strategy for Paths to get the record information
// we use
readAllBytes() strategy for Files to peruse byted information from the
documents
Result1 =
new String(Files.readAllBytes(Paths.get(file)));
// return
result to the primary() strategy
bring result1
back;
}
}
Comments
Post a Comment