主java.lang.ClassCastException中的异常:class java.lang.String can't be cast to class

问题描述 投票:0回答:1

我在处理 json 数据时收到 clasCastException。

我想从 JSON 响应中获取“employeeid”,然后想在新的 Excel 文件中写入员工 ID。但是,我收到类转换异常 - 字符串无法转换为对象。

我已经在下面粘贴了我的代码,因为我是新手,所以非常感谢您的帮助。

这是我的 JSON 响应:


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

代码:

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();
        }
    }
    
}

java json api http httpresponse
1个回答
-1
投票

好吧,让我们让它更简单一点。一旦你有了 jsonString,你就可以做这样的事情 -

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"))

  }

}

之后你可以在任何你想要的文件中写入employeeIds列表

编辑

这里是写入csv文件的代码


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);
        }
    }

© www.soinside.com 2019 - 2024. All rights reserved.