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

huangapple go评论60阅读模式
英文:

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

问题

I am getting the classCastException while processing the JSON data.
我在处理JSON数据时遇到了ClassCastException。

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.
我想从JSON响应中获取"employeeid",然后将员工ID写入新的Excel文件。但是,我遇到了类转换异常 - 无法将String转换为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:
这是我的JSON响应:

Code:
代码:

英文:

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

答案1

得分: 1

好的让我们简化一下一旦你有了jsonString你可以像这样做 -

``` java
List<String> employeeIds = new ArrayList<>();
JSONObject obj = new JSONObject(jsonString);
if (obj.has("userdetails")) {
    // 获取userDetails数组对象
    JSONArray userDetails = obj.getJSONArray("userdetails");

    // 遍历
    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 + "/employeeIds.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);
    }
}

<details>
<summary>英文:</summary>
okay let&#39;s make it bit simpler. Once you have the jsonString, you can do something like this - 
``` java
List&lt;String&gt; employeeIds = new ArrayList&lt;&gt;();
JSONObject obj = new JSONObject(jsonString);
if (obj.has(&quot;userdetails&quot;)) {
// get the userDetails array object
JSONArray userDetails = obj.getJSONArray(&quot;userdetails&quot;);
// loop over
for (int i = 0; i &lt; userDetails.length(); i++) {
JSONObject object = (JSONObject) userDetails.get(i);
employeeIds.add(object.getString(&quot;employeeid&quot;))
}
}

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&lt;String&gt; employeeIds, String directoryLocation) {
        String fileName = directoryLocation + &quot;/empoyeeIds.csv&quot; ;
        try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), StandardCharsets.UTF_8))) {
            String header = &quot;Employee Ids&quot;;
            bw.write(header);
            bw.newLine();
            for (String id : employeeIds) {
                bw.write(id);
                bw.newLine();
            }
        } catch (UnsupportedEncodingException e) {
            LOG.error(&quot;Unsupported encoding format&quot;, e);
        } catch (FileNotFoundException e) {
            LOG.error(&quot;Error creating the file &quot;, e);
        } catch (IOException e) {
            LOG.error(&quot;Error creating csv file&quot;, e);
        }
    }

huangapple
  • 本文由 发表于 2023年4月13日 21:57:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76006320.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定