Give an example how JSON text can be read in Java using JSON.simple APIs and parser?

Answered

Give an example how JSON text can be read in Java using JSON.simple APIs and parser?

Ninja Asked on 19th September 2018 in JSON.
Add Comment
1 Answer(s)
Best answer

Consider the following text in JSON file emp.json for reading:

{

“empname”:”James”,

“age”: 25,

“location”:”Bangalore”,

“skills”:[“Java”, “Spring”, “Hibernate”, “WebServices”]

}

To read this file in Java, first JSON.simple API and parsers have to be installed. The following Java code will read the content from JSON file and display appropriately.


public class JsonExample {

public static void main(String[] args) {

// Parser from JSON.simple

JSONParser parser = new JSONParser();

try {

Object obj = parser.parse(new FileReader("c:\\Users\\username\\Desktop\\emp.json"));

// JSONObject - API from JSON.simple

JSONObject jsonObject = (JSONObject) obj;

String empname = (String)jsonObject.get("empname");

System.out.println(empname);

long age = (Long) jsonObject.get("age");

System.out.println(age);

String location = (String) jsonObject.get("location");

System.out.println(location);

// JSONArray - API for array

JSONArray skills = (JSONArray) jsonObject.get("skills");

Iterator<String> iterator = skills.iterator();

while (iterator.hasNext()) {

System.out.println(iterator.next());

}

} catch (FileNotFoundException e) { e.printStackTrace(); }

catch (IOException e) { e.printStackTrace(); }

catch (ParseException e) { e.printStackTrace(); }

}

}

Ninja Answered on 19th September 2018.
Add Comment