java.lang.ClassCastException:org.json.JSONObject $ Null无法强制转换为java.lang.String

时间:2018-01-04 11:06:03

标签: json spring

例外java.lang.ClassCastExceptionorg.json.JSONObject$Null无法转换为java.lang.String

Printthis>>>>>>userName=user1&passKey=12345678 POST Response Code :: 200

jsonObj>>>>>>>>>>>>>>>>>>{"response":{"roleTitle":"Parent","roleId":146,"passKey":"12345678","id":1,"userName":"user1"},"errorCode":null,"error":false,"message":null}

Jan 04, 2018 4:33:11 PM org.apache.catalina.core.StandardWrapperValve invoke SEVERE: Servlet.service() for servlet [spring-dispatcher] in context with path [/balihans] threw exception [Request processing failed; nested exception is java.lang.ClassCastException: org.json.JSONObject$Null cannot be cast to java.lang.String] with root cause java.lang.ClassCastException: org.json.JSONObject$Null cannot be cast to java.lang.String at com.swasth.general.controller.SwasthController.postLogin(SwasthController.java:2274) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:777) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868) at javax.servlet.http.HttpServlet.service(HttpServlet.java:650) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842) at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Unknown Source)

这是我的postLogin代码

@RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView postLogin(HttpServletRequest request,HttpServletRequest response) throws IOException, JSONException {

    ModelAndView addmodel = new ModelAndView("login");
    String uri = "http://localhost:8080/login/api/";
    URL url = new URL(uri);
    HttpURLConnection con = (HttpURLConnection)url.openConnection();
    con.setRequestMethod("POST");

    String userName = request.getParameter("userName");
    String passKey = request.getParameter("passKey");
    con.setDoOutput(true);
    OutputStream os = con.getOutputStream();

    os.write(("userName=" + userName + "&passKey=" + passKey).getBytes());
    System.out.println("Printthis>>>>>>" + "userName=" + userName + "&passKey=" + passKey);
    os.flush();
    os.close();

    int responseCode = con.getResponseCode();
    System.out.println("POST Response Code :: " + responseCode);        

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer responses = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        responses.append(inputLine);
    }
    //System.out.println("responses>>>>>>>>>>>"+responses);

    String str = responses.toString();
    JSONObject jsonObj = new JSONObject(str);

    System.out.println("jsonObj>>>>>>>>>>>>>>>>>>"+jsonObj);

    String res = (String)jsonObj.get("errorCode");

    // build a JSON object

    List<PatentLoginInfo> PatentLoginInfoArray = new ArrayList<PatentLoginInfo>();
    ObjectMapper mapper = new ObjectMapper();       

    RestTemplate restTemplate = new RestTemplate();

    String res11 = (String)jsonObj.get("response");
    String login = restTemplate.getForObject(uri, String.class);
    JSONObject obj = new JSONObject(login);
    JSONObject objects = obj.getJSONObject(res11);

    System.out.println("objects>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+objects);

    PatentLoginInfo patentLoginInfo = mapper.readValue(objects.toString(), PatentLoginInfo.class);
     PatentLoginInfoArray.add(patentLoginInfo);

    addmodel.addObject("theLogin", PatentLoginInfoArray);

    if (res.equals("BVE000403")) { // success

        addmodel = new ModelAndView("index");
        addmodel.addObject("login Unsucessfull","Password is invalid");

        return addmodel;
    } 
    else{

            addmodel = new ModelAndView("AnswerQuestion");
            addmodel.addObject("login sucessfull");
            return addmodel;

    }
}

3 个答案:

答案 0 :(得分:7)

JSONObject有一个特定的内部常量,用于表示空对象:JSONObject.NULL

在将JSONObject转换为String之前,您可以验证它是否等于NULL常量。这是一个例子:

//put words from JSON to array
for (int i = 0; i<wordsInJSONArray.length(); i++) {
    Object o = wordsInJSONArray.get(i);
    if (!JSONObject.NULL.equals(o)) {
        String word = (String) o;
        this.wordsArray[i] = word;
    }
}

答案 1 :(得分:2)

似乎"errorCode"在您的版面中为空:

{"roleTitle":"Parent","roleId":146,"passKey":"12345678","id":1,"userName":"user1"},"errorCode":null,"error":false,"message":null}

因此,您需要在转换为字符串

之前检查null

String res = (String)jsonObj.get("errorCode");

所以应用以下验证,它将起作用:

String res = null;
if (!org.json.JSONObject.NULL.equals(jsonObj.opt("errorCode")) && jsonObj.getString("errorCode") != null) {
    res = jsonObj.getString("errorCode");
}

答案 2 :(得分:0)

您还可以使用isNull()

如果指定名称的关联值是JsonValue.NULL,则返回true。更多here

因此您的代码应为:

String code = jsonObj.isNull("errorCode") ? "" : jsonObj.getJsonString("errorCode");