This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 5 years ago.
i have problem to parse my json data,
this is my json data :
{"data":
[
{"ean": "222222","itemname": "","location": "001010202,001010201","po":[
{"ponumber": 1,"qty": 22
},
{"ponumber": 2,"qty": 33
}
]
},
{
"ean": "11112222",
"itemname": "เหงือก",
"location": "001010601",
"po": [
{
"ponumber": 1,
"qty": 7
}
]
},
{
"ean": "22223333",
"itemname": "Crystal Water",
"location": "001010410,001010401",
"po": [
{
"ponumber": 3,
"qty": 13
}
]
}
]}
i want to show the output like :
thank you
this is my java code to parsing json data and show to listview :
void parseJsonData(String jsonString) throws JSONException {
String data = "";
String data2 = null;
List<String> list = new ArrayList<>();
JSONObject json = new JSONObject(jsonString);
JSONArray arrayData = json.getJSONArray("data");
for (int i = 0; i < arrayData.length(); i++) {
JSONObject jsonDataArray = arrayData.getJSONObject(i);
String ean = jsonDataArray.getString("ean");
String itemname = jsonDataArray.getString("itemname");
String locations = jsonDataArray.getString("location");
data = "\n EAN = " + ean +
"\n Item Name = " + itemname +"\n";
JSONArray arrayPO = jsonDataArray.getJSONArray("po");
for (int j = 0; j < arrayPO.length(); j++ ) {
JSONObject jsonPO = arrayPO.getJSONObject(j);
ponumb = jsonPO.getString("ponumber");
qty = jsonPO.getString("qty");
//int numb = i + 1;
data2 = "\n PO Number : " + ponumb +
"\n Quantity : " + qty + "\n";
list.add(data+data2);
System.err.println(data+data2);
}
}
ArrayAdapter<String> LVarray;
LVarray = new ArrayAdapter<String>(ListActivity.this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(LVarray);
}
this is screen shot the output:
1.You can use StringBuilder to save the data2(po List).
2.In the inner for loop ,you can use append method to add it in it .
3.Get the length of StringBuilder .Then remove the saved data2.
4.Then you can save again .
Edit
public void parseJsonData(String jsonString) throws JSONException {
String data = "";
StringBuilder data2 = new StringBuilder();
List<String> list = new ArrayList<>();
JSONObject json = new JSONObject(jsonString);
JSONArray arrayData = json.getJSONArray("data");
for (int i = 0; i < arrayData.length(); i++) {
JSONObject jsonDataArray = arrayData.getJSONObject(i);
String ean = jsonDataArray.getString("ean");
String itemname = jsonDataArray.getString("itemname");
String locations = jsonDataArray.getString("location");
data = "\n EAN = " + ean +
"\n Item Name = " + itemname + "\n";
JSONArray arrayPO = jsonDataArray.getJSONArray("po");
for (int j = 0; j < arrayPO.length(); j++) {
JSONObject jsonPO = arrayPO.getJSONObject(j);
ponumb = jsonPO.getString("ponumber");
qty = jsonPO.getString("qty");
//int numb = i + 1;
data2.append("\n PO Number : " + ponumb +
"\n Quantity : " + qty + "\n");
list.add(data + data2);
}
System.err.println(data + data2);
int sb_length = data2.length();
data2.delete(0, sb_length);
}
}
this also can help
try {
//Get root array
JSONArray data_array = jsonObject.getJSONArray("data");
for (int i=0;i<data_array.length();i++){
JSONObject jsonObject1 = array.getJSONObject(i);
String ean = jsonObject1.optString("ean");
String itemname = jsonObject1.optString("itemname");
String location = jsonObject1.optString("location");
JSONArray child_Array = jsonObject1.getJSONArray("po");
for (int j=0;j<childArray.length();j++){
JSONObject childJosnObject = array.getJSONObject(i);
String ponumber = jsonObject1.optString("ponumber");
String qty = jsonObject1.optString("qty");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
You have to try like this, it will help you
JsonParseModel jsonParseModel = new Gson().fromJson(jsonString,JsonParseModel.class);
public class JsonParseModel {
private ArrayList<DataClass> data;
public ArrayList<DataClass> getData() {
return data;
}
public void setData(ArrayList<DataClass> data) {
this.data = data;
}
public class DataClass{
private String ean,itemname,location;
private ArrayList<PoData> po;
public String getEan() {
return ean;
}
public void setEan(String ean) {
this.ean = ean;
}
public String getItemname() {
return itemname;
}
public void setItemname(String itemname) {
this.itemname = itemname;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public ArrayList<PoData> getPo() {
return po;
}
public void setPo(ArrayList<PoData> po) {
this.po = po;
}
public class PoData{
private int ponumber,qty;
public int getPonumber() {
return ponumber;
}
public void setPonumber(int ponumber) {
this.ponumber = ponumber;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
}
}
}
private void parseJsondata(String response) {
try {
// response
JSONObject jsonObject = new JSONObject(response);
// get data from JSONArray
JSONArray data = jsonObject.getJSONArray("data");
// for loop to your JSONArray's Strings
for (int i = 0; i < data.length(); i++) {
// get JSONObject from i
JSONObject jo = data.getJSONObject(i);
// get string
String ean = jo.getString("ean");
String itemname = jo.getString("itemname");
String location = jo.getString("location");
JSONArray jA = jo.getJSONArray("po");
for (int j = 0; j < jA.length(); j++) {
// get JSONObject by jO
JSONObject jO = jA.getJSONObject(i);
// get string
String ponumber = jO.getString("ponumber");
String qty = jO.getString("qty");
}
}
//Log response
Log.e("response:", response);
} catch (JSONException e) {
e.printStackTrace();
}
}
public static void runClient() throws JSONException {
String httpServerHostAddr = "127.0.0.1";
int httpServerPort = Constants.HTTP_SERVER_PORT;
ProductResource clientHandle = ClientResource.create(
"http://" + httpServerHostAddr + ":" + httpServerPort + "/student", ProductResource.class);
StudentDTO student = new StudentDTO();
System.out.println("TEST Starting\n");
student.setStudentNo("123456789");
student.setName("Jhon");
student.setSurname("Gibson");
student.setIdentityNumber("15423200");
student.setSex(Byte.valueOf("0"));
student.setFacultyId(Byte.valueOf("1"));
student.setDepartmentId(Byte.valueOf("2"));
JsonRepresentation jsonRep = student.toJsonRepresentation();
JsonRepresentation response = (JsonRepresentation) clientHandle.store(jsonRep);
StudentDTO responseStudent = new StudentDTO(response);
System.out.println("What's Stored: " + responseStudent.toString());
ProductResource clientHandle2 = ClientResource.create(
"http://" + httpServerHostAddr + ":" + httpServerPort + "/student/"
+ responseStudent.getStudentId(), ProductResource.class);
response = (JsonRepresentation) clientHandle2.represent();
responseStudent = new StudentDTO(response);
System.out.println("\nWhat's retrieved: " + responseStudent.toString());
Above code is my main code for testing the project
#Override
public JsonRepresentation toJsonRepresentation() throws SystemException {
try {
JSONObject jsonObjectRep = new JSONObject();
if (this.getExitCode() == Constants.EXIT_SUCCESS) {
jsonObjectRep.put("studentId", this.getStudentId());
jsonObjectRep.put("studentNo", this.getStudentNo());
jsonObjectRep.put("name", this.getName());
jsonObjectRep.put("surname", this.getSurname());
jsonObjectRep.put("identityNumber", this.getIdentityNumber());
jsonObjectRep.put("birthDate",this.getBirthDate());
jsonObjectRep.put("sex", this.getSex());
jsonObjectRep.put("facultyId", this.getFacultyId());
jsonObjectRep.put("departmentId", this.getDepartmentId());
jsonObjectRep.put("educationYear", this.getEducationYear());
jsonObjectRep.put("educationStatus", this.getEducationStatus());
jsonObjectRep.put("macAdress", this.getMacAdress());
jsonObjectRep.put("exitCode", this.getExitCode());
} else {
jsonObjectRep.put("exitCode", this.getExitCode());
}
JsonRepresentation jsonRep = new JsonRepresentation(jsonObjectRep);
return jsonRep;
} catch (JSONException ex) {
SystemException e = SystemException.wrap(ex, ValidationCode.UNABLE_TO_PRODUCE_JSON_REPRESENTATION);
throw e;
}
}
The above code snippet shows how I created my JSON object
#Override
protected void fromJsonRepresentation(JsonRepresentation json) throws SystemException {
try {
JSONObject jsonObj;
jsonObj = json.getJsonObject();
this.studentId = jsonObj.getInt("studentId");
this.studentNo = jsonObj.getString("studentNo");
this.name = jsonObj.getString("name");
this.surname = jsonObj.getString("surname");
this.identityNumber = jsonObj.getString("identityNumber");
try {
this.birthdate = sFormat.parse(jsonObj.getString("birthDate"));
} catch (ParseException ex) {
Logger.getLogger(StudentDTO.class.getName()).log(Level.SEVERE, null, ex);
}
this.sex = (byte) jsonObj.getInt("sex");
this.facultyId = (byte) jsonObj.getInt("facultyId");
this.departmentId = (byte) jsonObj.getInt("departmentId");
this.educationYear = (byte) jsonObj.getInt("educationYear");
this.educationStatus = (byte) jsonObj.getInt("educationStatus");
this.macAdress = jsonObj.getString("macAdress");
this.setExitCode(jsonObj.getInt("exitCode"));
} catch (JSONException ex) {
SystemException e = SystemException.wrap(ex, ValidationCode.UNABLE_TO_PARSE_JSON);
throw e;
}
}
And this here I'm trying to parse into the JSON object in code. I am getting this error org.json.JSONException: JSONObject["studentId"] not found.
When my system loads the text file with the data already in it,it always initialises the integers for restaurantTables and restaurantSeats to 0? How do I stop this from happening and keep the figures assigned when adding to the system?
Here is the code which changes it back to 0:
public class TextRestaurantDAO extends RestaurantDAO {
static final char DELIMITER=':';
#Override
public List<Restaurant> loadRestaurants(Path path) {
List<Restaurant> restaurants = new ArrayList<>();
try (Scanner s = new Scanner(new BufferedReader(new FileReader(path.toString())))) {
s.useDelimiter(Character.toString(DELIMITER));
Restaurant r;
int restaurantId, restaurantTables, restaurantSeats;
String restaurantName, restaurantLocation;
while (s.hasNext()) {
if (s.hasNextInt()) {
restaurantId = s.nextInt();
}
else {
restaurantId = 0;
}
if (s.hasNextInt()) {
restaurantTables = s.nextInt();
}
else {
restaurantTables = 0;
}
if (s.hasNextInt()) {
restaurantSeats = s.nextInt();
}
else {
restaurantSeats = 0;
}
restaurantName = s.next();
restaurantLocation = s.next();
s.nextLine();
r = new Restaurant(restaurantId, restaurantName, restaurantLocation, restaurantTables, restaurantSeats);
restaurants.add(r);
}
s.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(TextCustomerDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return restaurants;
}
#Override
public void storeRestaurants(Path path, List<Restaurant> restaurants) {
try (PrintWriter output = new PrintWriter(path.toFile())) {
for (Restaurant r:restaurants) {
output.println(toFileString(r));
}
output.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(TextRestaurantDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
public String toFileString(Restaurant r) {
return Integer.toString(r.getRestaurantId()) + DELIMITER +
r.getRestaurantName() + DELIMITER +
r.getRestaurantLocation() + DELIMITER +
r.getRestaurantTables() + DELIMITER +
r.getRestaurantSeats() + DELIMITER;
}
}
If you could help it would be much appreciated.
Here is an example of what the text file has before it loads:
1:Riva:Bothwell:31:78:
After it Loads:
1:Riva:Bothwell:0:0:
How do i stop this from happening?
Thankyou
if you require more code please ask
I am trying to write an automated Java test where the code will go to a specified URL, read the JSON data and print it up.
Here is the JSON I am trying to access;
{
"status": "success",
"records": [
{
"timestamp": 1381222871868,
"deviceId": "288",
"temperature": 17
},
{
"timestamp": 1381222901868,
"deviceId": "288",
"temperature": 17
},
{
"timestamp": 1381222931868,
"deviceId": "288",
"temperature": 17
},
]}
As you can see I only have 3 elements, Timestamp, DeviceId and Temperature.
What I am ultimately aiming for it to be able to get 2 Timestamp values and take one value away from the other, if that is possible.
Anyway I have been trying to do this all day and am having no luck whatsoever. I was recommended to use Gson and I have included the jar files into my classpath.
If anyone knows anything or can help me in any way it would be much appreciated as I have exhausted Google and myself trying to work this out.
Here is the code I have to display the full list, but I do not fully understand it and so far can't manipulate it to my advantage;
public static void main(String[] args) throws Exception
{
String jsonString = callURL("http://localhost:8000/eem/api/v1/metrics/temperature/288");
System.out.println("\n\njsonString: " + jsonString);
// Replace this try catch block for all below subsequent examples
/*try
{
JSONArray jsonArray = new JSONArray(jsonString);
System.out.println("\n\njsonArray: " + jsonArray);
}
catch (JSONException e)
{
e.printStackTrace();
}*/
try
{
JSONArray jsonArray = new JSONArray(jsonString);
int count = jsonArray.length(); // get totalCount of all jsonObjects
for(int i=0 ; i< count; i++)
{ // iterate through jsonArray
JSONObject jsonObject = jsonArray.getJSONObject(i); // get jsonObject # i position
System.out.println("jsonObject " + i + ": " + jsonObject);
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
public static String callURL(String myURL)
{
//System.out.println("Requested URL:" + myURL);
StringBuilder sb = new StringBuilder();
URLConnection urlConn = null;
InputStreamReader in = null;
try
{
URL url = new URL(myURL);
urlConn = url.openConnection();
if (urlConn != null)
{
urlConn.setReadTimeout(60 * 1000);
}
if (urlConn != null && urlConn.getInputStream() != null)
{
in = new InputStreamReader(urlConn.getInputStream(),
Charset.defaultCharset());
BufferedReader bufferedReader = new BufferedReader(in);
if (bufferedReader != null)
{
int cp;
while ((cp = bufferedReader.read()) != -1)
{
sb.append((char) cp);
}
bufferedReader.close();
}
}
in.close();
}
catch (Exception e)
{
throw new RuntimeException("Exception while calling URL:"+ myURL, e);
}
return sb.toString();
}
Cheers
I had read the values from file but you can read from URL, the extracting process code is present inside extractJson() method.
public static void main(String [] args)
{
try
{
FileInputStream fis=new FileInputStream("testjson.json");
int b=0;
String val="";
while((b=fis.read())!=-1)
{
val=val+(char)b;
}
extractJson(val);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void extractJson(String json)
{
try
{
JSONObject jobject=new JSONObject(json);
System.out.println("Json object Length: "+jobject.length());
System.out.println("Status: "+jobject.getString("status"));
JSONArray jarray=new JSONArray(jobject.getString("records"));
System.out.println("Json array Length: "+jarray.length());
for(int j=0;j<jarray.length();j++)
{
JSONObject tempObject=jarray.getJSONObject(j);
System.out.println("Timestamp: "+tempObject.getString("timestamp"));
System.out.println("Device Id: "+tempObject.getString("deviceId"));
System.out.println("Temperature: "+tempObject.getString("temperature"));
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
You could use ArrayList to store the values which will be available inside for loop. From your question you need to pass jsonString this variable to the extractJson() method. Use org.json jar file to process json. If you could alter this for gson then it'll be good for your requirement.
here's how to do it via Google-Gson
class MyRecord
{
private long timestamp;
private String deviceId;
private Integer temperature;
//Getters & setters
}
public static void main(String... args){
String myJsonString=callUrl("http://mydomain.com/x.json");
JsonParser jp = new JsonParser();
JsonElement ele = jp.parse(myJsonString);
Gson gg = new Gson();
Type type = new TypeToken<List<MyRecord>>() {
}.getType();
List<MyRecord> lst= gg.fromJson(ele.getAsJsonObject().get("records"), type);
//Now the json is parsed in a List of MyRecord, do whatever you want to with it
}
An "high-level" Gson parsing answer:
package stackoverflow.questions.q19252374;
import java.util.List;
import com.google.gson.Gson;
public class Q19252374 {
class Record {
Long timestamp;
String deviceId;
Long temperature;
}
class Container {
List<Record> records;
}
public static void main(String[] args) {
String json = "{ \"status\": \"success\", \"records\": [{\"timestamp\": 1381222871868,\"deviceId\": \"288\",\"temperature\": 17 },{\"timestamp\": 1381222901868,\"deviceId\": \"288\",\"temperature\": 17 },{\"timestamp\": 1381222931868,\"deviceId\": \"288\",\"temperature\": 17 } ]} ";
Gson g = new Gson();
Container c = g.fromJson(json, Container.class);
for (Record r : c.records)
System.out.println(r.timestamp);
}
}
Of course this is the result:
1381222871868
1381222901868
1381222931868
I want to read this JSON file with java using json simple library.
My JSON file looks like this:
[
{
"name":"John",
"city":"Berlin",
"cars":[
"audi",
"bmw"
],
"job":"Teacher"
},
{
"name":"Mark",
"city":"Oslo",
"cars":[
"VW",
"Toyata"
],
"job":"Doctor"
}
]
This is the java code I wrote to read this file:
package javaapplication1;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JavaApplication1 {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("c:\\file.json"));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
System.out.println(name);
String city = (String) jsonObject.get("city");
System.out.println(city);
String job = (String) jsonObject.get("job");
System.out.println(job);
// loop array
JSONArray cars = (JSONArray) jsonObject.get("cars");
Iterator<String> iterator = cars.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
But I get the following exception:
Exception in thread "main" java.lang.ClassCastException:
org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject
at javaapplication1.JavaApplication1.main(JavaApplication1.java:24)
Can somebody tell me what I am doing wrong? The whole file is a array and there are objects and another array (cars) in the whole array of the file. But i dont know how I can parse the whole array into a java array. I hope somebody can help me with a code line which I am missing in my code.
Thanks
The whole file is an array and there are objects and other arrays (e.g. cars) in the whole array of the file.
As you say, the outermost layer of your JSON blob is an array. Therefore, your parser will return a JSONArray. You can then get JSONObjects from the array ...
JSONArray a = (JSONArray) parser.parse(new FileReader("c:\\exer4-courses.json"));
for (Object o : a)
{
JSONObject person = (JSONObject) o;
String name = (String) person.get("name");
System.out.println(name);
String city = (String) person.get("city");
System.out.println(city);
String job = (String) person.get("job");
System.out.println(job);
JSONArray cars = (JSONArray) person.get("cars");
for (Object c : cars)
{
System.out.println(c+"");
}
}
For reference, see "Example 1" on the json-simple decoding example page.
You can use jackson library and simply use these 3 lines to convert your json file to Java Object.
ObjectMapper mapper = new ObjectMapper();
InputStream is = Test.class.getResourceAsStream("/test.json");
testObj = mapper.readValue(is, Test.class);
Add Jackson databind:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0.pr2</version>
</dependency>
Create DTO class with related fields and read JSON file:
ObjectMapper objectMapper = new ObjectMapper();
ExampleClass example = objectMapper.readValue(new File("example.json"), ExampleClass.class);
Reading from JsonFile
public static ArrayList<Employee> readFromJsonFile(String fileName){
ArrayList<Employee> result = new ArrayList<Employee>();
try{
String text = new String(Files.readAllBytes(Paths.get(fileName)), StandardCharsets.UTF_8);
JSONObject obj = new JSONObject(text);
JSONArray arr = obj.getJSONArray("employees");
for(int i = 0; i < arr.length(); i++){
String name = arr.getJSONObject(i).getString("name");
short salary = Short.parseShort(arr.getJSONObject(i).getString("salary"));
String position = arr.getJSONObject(i).getString("position");
byte years_in_company = Byte.parseByte(arr.getJSONObject(i).getString("years_in_company"));
if (position.compareToIgnoreCase("manager") == 0){
result.add(new Manager(name, salary, position, years_in_company));
}
else{
result.add(new OrdinaryEmployee(name, salary, position, years_in_company));
}
}
}
catch(Exception ex){
System.out.println(ex.toString());
}
return result;
}
Use google-simple library.
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
Please find the sample code below:
public static void main(String[] args) {
try {
JSONParser parser = new JSONParser();
//Use JSONObject for simple JSON and JSONArray for array of JSON.
JSONObject data = (JSONObject) parser.parse(
new FileReader("/resources/config.json"));//path to the JSON file.
String json = data.toJSONString();
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
Use JSONObject for simple JSON like {"id":"1","name":"ankur"} and JSONArray for array of JSON like [{"id":"1","name":"ankur"},{"id":"2","name":"mahajan"}].
Might be of help for someone else facing the same issue.You can load the file as string and then can convert the string to jsonobject to access the values.
import java.util.Scanner;
import org.json.JSONObject;
String myJson = new Scanner(new File(filename)).useDelimiter("\\Z").next();
JSONObject myJsonobject = new JSONObject(myJson);
Gson can be used here:
public Object getObjectFromJsonFile(String jsonData, Class classObject) {
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject) parser.parse(jsonData);
return gson.fromJson(object, classObject);
}
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class Delete_01 {
public static void main(String[] args) throws FileNotFoundException,
IOException, ParseException {
JSONParser parser = new JSONParser();
JSONArray jsonArray = (JSONArray) parser.parse(new FileReader(
"delete_01.json"));
for (Object o : jsonArray) {
JSONObject person = (JSONObject) o;
String strName = (String) person.get("name");
System.out.println("Name::::" + strName);
String strCity = (String) person.get("city");
System.out.println("City::::" + strCity);
JSONArray arrays = (JSONArray) person.get("cars");
for (Object object : arrays) {
System.out.println("cars::::" + object);
}
String strJob = (String) person.get("job");
System.out.println("Job::::" + strJob);
System.out.println();
}
}
}
Following is the working solution to your problem statement as,
File file = new File("json-file.json");
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(file));
JSONArray jsonArray = new JSONArray(obj.toString());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
System.out.println(jsonObject.get("name"));
System.out.println(jsonObject.get("city"));
System.out.println(jsonObject.get("job"));
jsonObject.getJSONArray("cars").forEach(System.out::println);
}
Hope this example helps too
I have done java coding in a similar way for the below json array example as follows :
following is the json data format : stored as "EMPJSONDATA.json"
[{"EMPNO":275172,"EMP_NAME":"Rehan","DOB":"29-02-1992","DOJ":"10-06-2013","ROLE":"JAVA DEVELOPER"},
{"EMPNO":275173,"EMP_NAME":"G.K","DOB":"10-02-1992","DOJ":"11-07-2013","ROLE":"WINDOWS ADMINISTRATOR"},
{"EMPNO":275174,"EMP_NAME":"Abiram","DOB":"10-04-1992","DOJ":"12-08-2013","ROLE":"PROJECT ANALYST"}
{"EMPNO":275174,"EMP_NAME":"Mohamed Mushi","DOB":"10-04-1992","DOJ":"12-08-2013","ROLE":"PROJECT ANALYST"}]
public class Jsonminiproject {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
JSONArray a = (JSONArray) parser.parse(new FileReader("F:/JSON DATA/EMPJSONDATA.json"));
for (Object o : a)
{
JSONObject employee = (JSONObject) o;
Long no = (Long) employee.get("EMPNO");
System.out.println("Employee Number : " + no);
String st = (String) employee.get("EMP_NAME");
System.out.println("Employee Name : " + st);
String dob = (String) employee.get("DOB");
System.out.println("Employee DOB : " + dob);
String doj = (String) employee.get("DOJ");
System.out.println("Employee DOJ : " + doj);
String role = (String) employee.get("ROLE");
System.out.println("Employee Role : " + role);
System.out.println("\n");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.json;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class ReadJSONFile {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("C:/My Workspace/JSON Test/file.json"));
JSONArray array = (JSONArray) obj;
JSONObject jsonObject = (JSONObject) array.get(0);
String name = (String) jsonObject.get("name");
System.out.println(name);
String city = (String) jsonObject.get("city");
System.out.println(city);
String job = (String) jsonObject.get("job");
System.out.println(job);
// loop array
JSONArray cars = (JSONArray) jsonObject.get("cars");
Iterator<String> iterator = cars.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
This issue occurs when you are importing the org. json library for JSONObject class. Instead you need to import org.json.simple library.
private static final JsonParser JSON_PARSER = new JsonParser();
private static final String FILE_PATH = "configuration/data.json";
private JsonObject readJsonDataFromFile() {
try {
File indexFile = new File(FILE_PATH);
String fileData = Files.toString(indexFile, Charsets.UTF_8);
return (JsonObject) JSON_PARSER.parse(fileData);
} catch (IOException | JsonParseException e) {
String error = String.format("Error while reading file %s", FILE_PATH);
log.error(error);
throw new RuntimeException(error, e);
}
}
public class JsonParser {
public static JSONObject parse(String file) {
InputStream is = JsonParser.class.getClassLoader().getResourceAsStream(file);
assert is != null;
return new JSONObject(new JSONTokener(is));
}
}
// Read Json
JSONObject deviceObj = new JSONObject(JsonParser.parse("Your Json filename").getJSONObject(deviceID).toString());
Perform logic to iterate
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class JsonParserTest {
public static void main(String[] args) throws IOException {
String data = new String(Files.readAllBytes(Paths.get("C:/json.txt")));
JsonElement jsonElement = JsonParser.parseString(data);
JsonObject json = jsonElement.getAsJsonObject();
System.out.println(json.get("userId"));
System.out.println(json.get("id"));
System.out.println(json.get("title"));
System.out.println(json.get("completed"));
}
}
Use the below repositay from GSON.
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
Sample Json
{
"per_page": 3,
"total": 12,
"data": [{
"last_name": "Bluth",
"id": 1,
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg",
"first_name": "George"
},
{
"last_name": "Weaver",
"id": 2,
//"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg",
"first_name": "Janet"
},
{
"last_name": "Wong",
"id": 3,
//"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg",
"first_name": "Emma"
}
],
"page": 1,
"total_pages": 4
}
First If statement will convert the single data from the body
Second if statement will differentiate the JsonArray object
public static String getvalueJpath(JSONObject responseJson, String Jpath ) {
Object obj = responseJson;
for(String s : Jpath.split("/"))
if (s.isEmpty())
if(!(s.contains("[") || s.contains("]")))
obj = ((JSONObject) obj).get(s);
else
if(s.contains("[") || s.contains("]"))
obj = ((JSONArray)((JSONObject)obj).get(s.split("\\[")[0])).get(Integer.parseInt(s.split("//[")[1].replaceAll("]", "")));
return obj.toString();
}
}
Solution using Jackson library. Sorted this problem by verifying the json on JSONLint.com and then using Jackson. Below is the code for the same.
Main Class:-
String jsonStr = "[{\r\n" + " \"name\": \"John\",\r\n" + " \"city\": \"Berlin\",\r\n"
+ " \"cars\": [\r\n" + " \"FIAT\",\r\n" + " \"Toyata\"\r\n"
+ " ],\r\n" + " \"job\": \"Teacher\"\r\n" + " },\r\n" + " {\r\n"
+ " \"name\": \"Mark\",\r\n" + " \"city\": \"Oslo\",\r\n" + " \"cars\": [\r\n"
+ " \"VW\",\r\n" + " \"Toyata\"\r\n" + " ],\r\n"
+ " \"job\": \"Doctor\"\r\n" + " }\r\n" + "]";
ObjectMapper mapper = new ObjectMapper();
MyPojo jsonObj[] = mapper.readValue(jsonStr, MyPojo[].class);
for (MyPojo itr : jsonObj) {
System.out.println("Val of getName is: " + itr.getName());
System.out.println("Val of getCity is: " + itr.getCity());
System.out.println("Val of getJob is: " + itr.getJob());
System.out.println("Val of getCars is: " + itr.getCars() + "\n");
}
POJO:
public class MyPojo {
private List<String> cars = new ArrayList<String>();
private String name;
private String job;
private String city;
public List<String> getCars() {
return cars;
}
public void setCars(List<String> cars) {
this.cars = cars;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
} }
RESULT:-
Val of getName is: John
Val of getCity is: Berlin
Val of getJob is: Teacher
Val of getCars is: [FIAT, Toyata]
Val of getName is: Mark
Val of getCity is: Oslo
Val of getJob is: Doctor
Val of getCars is: [VW, Toyata]
your json file look like this
import java.io.*;
import java.util.*;
import org.json.simple.*;
import org.json.simple.parser.*;
public class JSONReadFromTheFileTest {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("/Users/User/Desktop/course.json"));
JSONObject jsonObject = (JSONObject)obj;
String name = (String)jsonObject.get("Name");
String course = (String)jsonObject.get("Course");
JSONArray subjects = (JSONArray)jsonObject.get("Subjects");
System.out.println("Name: " + name);
System.out.println("Course: " + course);
System.out.println("Subjects:");
Iterator iterator = subjects.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
the output is
Name: Raja
Course: MCA
Subjects:
subject1: MIS
subject2: DBMS
subject3: UML
took it from here
try {
Object obj = parser.parse(new FileReader("C:/Local Disk/file.json"));
// JSONArray array = (JSONArray) obj;
JSONObject jsonObject = (JSONObject) obj;
JSONObject orchestration = (JSONObject) jsonObject.get("orchestration");
JSONObject trigger = (JSONObject) orchestration.get("trigger-definition");
JSONObject schedule = (JSONObject) trigger.get("schedule");
JSONObject trade = (JSONObject) schedule.get("trade-query");
// loop array
JSONArray filter = (JSONArray) trade.get("filter");
for (Object o : filter) {
JSONObject person = (JSONObject) o;
String strName = (String) person.get("name");
System.out.println("Name::::" + strName);
String operand = (String) person.get("operand");
System.out.println("City::::" + operand);
String value = (String) person.get("value");
System.out.println("value::::" + value);
}
JSONArray parameter = (JSONArray) trade.get("parameter");
for (Object o : parameter) {
JSONObject person = (JSONObject) o;
String strName = (String) person.get("name");
System.out.println("Name::::" + strName);
String value = (String) person.get("value");
System.out.println("value::::" + value);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
try {
//Object obj = parser.parse(new FileReader("C:/Local Disk/file.json"));
// create object mapper instance
ObjectMapper mapper = new ObjectMapper();
// convert JSON string to Book object
Object obj = mapper.readValue(Paths.get("C:/Local Disk/file.json").toFile(), Object.class);
// print book
System.out.println(obj);
String jsonInString = new Gson().toJson(obj);
JSONObject mJSONObject = new JSONObject(jsonInString);
System.out.println("value::::" + mJSONObject);
JSONObject orchestration = (JSONObject) mJSONObject.get("orchestration");
JSONObject trigger = (JSONObject) orchestration.get("trigger-definition");
JSONObject schedule = (JSONObject) trigger.get("schedule");
JSONObject trade = (JSONObject) schedule.get("trade-query");
// loop array
JSONArray filter = (JSONArray) trade.get("filter");
for (Object o : filter) {
JSONObject person = (JSONObject) o;
String strName = (String) person.get("name");
System.out.println("Name::::" + strName);
String operand = (String) person.get("operand");
System.out.println("City::::" + operand);
String value = (String) person.get("value");
System.out.println("value::::" + value);
}
JSONArray parameter = (JSONArray) trade.get("parameter");
for (Object o : parameter) {
JSONObject person = (JSONObject) o;
String strName = (String) person.get("name");
System.out.println("Name::::" + strName);
String value = (String) person.get("value");
System.out.println("value::::" + value);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You can use readAllBytes.
return String(Files.readAllBytes(Paths.get(filePath)),StandardCharsets.UTF_8);