Search code examples
javajsonapihttphttpresponse

Exception in main java.lang.ClassCastException:class java.lang.String can't be cast to class


I am getting the clasCastException while processing the json data.

I want to get "employeeid" from a JSON response and want to write later the employee IDs in a new Excel file. However, I am getting the class cast exception - String can not be cast into an Object.

I have pasted my code below as I am new to this so your help will be really appreciated.

here is my JSON Response:


{
    "msg": "Successful",
    "displaycount": "50",
    "totalcount": "1294",
    "userdetails": [
        {
            "employeeid": "132421",
            "userKey": 17
        },
        {
            "employeeid": "112342",
            "userKey": 18
        },
        {
            "employeeid": "112341",
            "userKey": 19
        },
        {
            "employeeid": "112343",
            "userKey": 20
        },
        {
            "employeeid": "99954",
            "userKey": 21
        },
    ],
    "errorCode": "0"
}

Code:

package api.src;

import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import com.opencsv.CSVWriter;
import java.io.*;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class callAPI {

     static String[] finalResult;
     public static void main(String[] args) throws URISyntaxException, IOException, InterruptedException, ParseException {

        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("*****"))
            .header("X-RapidAPI-Host", "***********")
            .header("Content-Type", "application/json")
            .header("Authorization",**********)
            .method("POST", HttpRequest.BodyPublishers.noBody())
            .build();

    System.out.println("Connected "+request);

    try {
        String path = "D:/Sonika/JARs/httpresponse.json";

        HttpResponse<String> response = null;
        response = HttpClient.newHttpClient().send(request, 
        HttpResponse.BodyHandlers.ofString());
        int statusCode = response.statusCode();
        System.out.println(statusCode);

        System.out.println(response.body());
        try (PrintWriter out = new PrintWriter(new FileWriter(path))) {
            out.write(response.body().toString());
        }

        JSONParser parse = new JSONParser();
        JSONObject jobj = (JSONObject) parse.parse(new FileReader(path));
        JSONArray jsonarr_1 = (JSONArray) jobj.get("userdetails");

        //Get data for userdetails array
        for (Object element : jsonarr_1) {
        //Store the JSON objects in an array
        //Get the index of the JSON object and print the values as per the index
        JSONObject jsonobj_1 = (JSONObject)element;
        finalResult =  (String[]) jsonobj_1.get("employeeid");
        System.out.println("\nEmployee ID: "+finalResult);

        }   
    }
    
    catch(IOException e) {
        // handle not expected exception
        e.printStackTrace();
    }
    }
    public void writingCSVFile(){
        try {
            CSVWriter  file = new CSVWriter(new FileWriter(new File("D:/Sonika/JARs/OutputExcelfile.xlsx")));
            String[] colName = { "Employee ID"};
            file.writeNext(colName);
            file.writeNext(finalResult);
            file.close();
        } 
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    
}


Solution

  • okay let's make it bit simpler. Once you have the jsonString, you can do something like this -

    List<String> employeeIds = new ArrayList<>();
    JSONObject obj = new JSONObject(jsonString);
    if (obj.has("userdetails")) {
    // get the userDetails array object
     JSONArray userDetails = obj.getJSONArray("userdetails");
    
    // loop over
     for (int i = 0; i < userDetails.length(); i++) {
        JSONObject object = (JSONObject) userDetails.get(i);
        employeeIds.add(object.getString("employeeid"))
    
      }
    
    }
    

    Later you can write the employeeIds list in any file you want

    EDITED

    here is the code to write in csv file

    
    public static void writeInCsv(List<String> employeeIds, String directoryLocation) {
            String fileName = directoryLocation + "/empoyeeIds.csv" ;
            try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), StandardCharsets.UTF_8))) {
                String header = "Employee Ids";
                bw.write(header);
                bw.newLine();
                for (String id : employeeIds) {
                    bw.write(id);
                    bw.newLine();
                }
            } catch (UnsupportedEncodingException e) {
                LOG.error("Unsupported encoding format", e);
            } catch (FileNotFoundException e) {
                LOG.error("Error creating the file ", e);
            } catch (IOException e) {
                LOG.error("Error creating csv file", e);
            }
        }