在main java.lang.ClassCastException中出现异常:class java.lang.String不能转换为class

lvmkulzt  于 2023-04-19  发布在  Java
关注(0)|答案(1)|浏览(144)

我在处理json数据时得到了clasCastException。
我想从JSON响应中获取“employeeid”,并希望稍后将员工ID写入新的Excel文件中。然而,我遇到了类强制转换异常-字符串无法转换为Object。
我已经粘贴我的代码如下,因为我是新的,所以你的帮助将非常感谢。
下面是我的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();
        }
    }
    
}
nuypyhwy

nuypyhwy1#

好的,让我们简单一点。一旦你有了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);
        }
    }

相关问题