0
In my java system appeared this error:
I’m sweating the POSTMAN tool to study the case.
HTTP Status 500 - org.json.Jsonobject cannot be cast to jdk.nashorn.api.scripting.Jsobject
Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;
import jdk.nashorn.api.scripting.JSObject;
/**
* Servlet implementation class teste1
*/
@WebServlet("/teste1")
public class teste1 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public teste1() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String nome = request.getParameter("nome");
PrintWriter saida = response.getWriter();
saida.println("teste1: "+nome);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
JSONObject json = (JSONObject) formatJson(request.getReader());
System.out.println(json.toString());
doGet(request, response);
formatJson(request.getReader());
String body = request.getReader().lines().reduce("",(acc, actual)->acc+actual );
System.out.println(body);
}
private JSObject formatJson(BufferedReader reader){
StringBuffer bs = new StringBuffer();
String line = null;
try{
while((line = reader.readLine()) != null){
bs.append(line);
}
}catch(Exception e){
e.getStackTrace();
}
JSONObject json = new JSONObject(bs.toString());
return (JSObject) json;
}
}
How should I proceed to find the solution to this error ?
The line
return (JSObject) json;
will throw an error necessarily. Types are distinct. Try another way to turn the string intoJSObject
– Jefferson Quesado
Any suggestions ???
– alexjosesilva
Use a single JSON library
– Jefferson Quesado
Look at your Miles :
import org.json.JSONObject; import jdk.nashorn.api.scripting.JSObject;
are two separate libraries– Jefferson Quesado
Removes the import
jdk.nashorn.api.scripting.JSObject
In the formatJson method you create an objectJSONObject
and converts toJSObject
. Then on that line, you reverse what you did earlier: ;JSONObject json = (JSONObject) formatJson(request.getReader());
does not make sense to do this, only works with theJSONObject
– Isaias Tavares