JSON Read Example

May 22, 2018 81 0 1

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 File

JSONExample.txt

{
"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"
}
}

Code

here we read all the json data in file
Object obj = new JSONParser().parse(new FileReader("JSONExample.txt"));
JSONObject jsonObject = (JSONObject) obj;
String id = jsonObject.get("id").toString();
System.out.println(id);
String name = jsonObject.get("name").toString();
System.out.println(name);
String surname = jsonObject.get("surname").toString();
System.out.println(surname);
JSONArray list = (JSONArray) jsonObject.get("lang");

Iterator i = list.iterator();
while (i.hasNext()){
JSONObject innerObj = (JSONObject) i.next();
System.out.println("Lang : "+innerObj.get("lang")+" Level : "+innerObj.get("knowledge"));
}

JSONObject job = (JSONObject) jsonObject.get("job");
System.out.println(job.get("site"));
System.out.println(job.get("name"));
System.out.println(job.get("salary"));
System.out.println(job.get("email"));

Screen Output :

20141434
RIDVAN
CAKIR
Lang : android Level : proficient
Lang : java Level : advanced
Lang : php Level : advanced
www.ridvancakir.com.tr
it specialist
6000$
ridvancakirtr@gmail.com

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 *