Java JSON Write File

May 22, 2018 72 0 0

Set the Environment

Before start coding we have to set a proper environment for the compiler, in order to recognize the JSON’s classes
Please download the files on the link below and add them to the project.
Java Json Jar
Java Json Simple

JSON Write on the File


JSONObject obj=new JSONObject();
obj.put("id","20141434");
obj.put("name","RIDVAN");
obj.put("surname","CAKIR");

Create the object file here.More than one child is created in an object using HASHMAP. You will understand easily by examining the example.We created “lang” child.

HashMap<String,String> lang1 = new HashMap<>(); //child 1
lang1.put("lang","android");
lang1.put("knowledge","proficient");
HashMap<String,String> lang2 = new HashMap<>();//child 2
lang2.put("lang","java");
lang2.put("knowledge","advanced");
HashMap<String,String> lang3 = new HashMap<>();//child 3
lang3.put("lang","php");
lang3.put("knowledge","advanced");

Created children were put into the Json Array immediately after obj (first object belong) into put JSONArray

JSONArray b = new JSONArray();
b.put(lang1);
b.put(lang2);
b.put(lang3);
obj.put("lang",b); // put ArrayObject


Here we have added more than child "job object" using HashMap. obj (first object belong) into put and write txt file.
HashMap<String,String> job = new HashMap<>();
job.put("name","it specialist");
job.put("salary","6000$");
job.put("site","www.ridvancakir.com.tr");
job.put("email","ridvancakirtr@gmail.com");
obj.put("job",job);
System.out.println(obj);
PrintWriter pw = new PrintWriter("JSONExample.txt");
pw.write(obj.toString());
pw.flush();
pw.close();

Screen Output :

{
"surname":"CAKIR",
"name":"RIDVAN",
"id":"20141434",
"lang":[
{
"lang":"android",
"knowledge":"proficient"
},
{
"lang":"java",
"knowledge":"advanced"
},
{
"lang":"php",
"knowledge":"advanced"
}
],
"job":{
"site":"www.ridvancakir.com.tr",
"name":"it specialist",
"salary":"6000$",
"email":"ridvancakirtr@gmail.com"
}
}

Reading the file in the next article
JSON Read Example

Github Link

Categories: Java
share TWEET PIN IT SHARE share share
Leave a reply

Leave a Reply

Your email address will not be published. Required fields are marked *