Org json jsonobject cannot be cast to java lang string cannot

java.lang.ClassCastException: java.lang.String cannot be cast to org.json.JSONObject

It looks like the response you have is a JSON-ification of a HTTP response. Therefore the body is simply a string value taht encodes another JSON object, so you’ll need to parse the body value again.

@Arnaud When I do that I get this exception org.json.JSONException: JSONObject[«body»] is not a JSONObject.

2 Answers 2

  1. get body string: String bodyString= resp.getString(«body»);
  2. parse bodyString to jsonObject: JSONObject body= new JSONObject(bodyString);
  3. get the username: String usename= body.getString(«username»);

print what you get in your body string, see if it contains username and better share your code and output

this shouldn’t happen. Did you try the way I said above? if yes,can you share your code and error stacktrace please?

JSONObject is nothing but a map which works on key-value. If the value returned by a key is map(i.e. key-value pairs) then it can be cast into a JSONObject, but in your case getBody.get(«username») returns johntest@example.com which is a simple string and not a key-value pair hence you get this exception Use: JSONObject getBody = accountDetails.getJsonObject(«body») or you can use:

String bodyString= accountDetails.getString("body"); JSONObject getBody= new JSONObject(bodyString) 

and then use Object alreadyExits = ((String) getBody).get(«username»); and it should work just fine.

The json mentioned in the post is not a valid json, so can you please give the correct json so that it can be debugged..you can validate it on jsonformatter.curiousconcept.com

Читайте также:  Java response body json

Источник

json.simple.JSONObject cannot be cast to java.lang.String with AWS Lambda JAVA

I’am trying to parse the ‘Body’ from a POST request with a Java Lambda. I’am stuck on this error for a while.

 org.json.simple.JSONObject cannot be cast to java.lang.String 

Witch should work with the parsing i’am doing right ? The weird thing is the insert is working on local with JUNIT but not online after on AWS.

@Override public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException < logger = context.getLogger(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); Number user_id = null; String birthdate = null; Listcompany_id = new ArrayList(); String email = null; String employment_status = null; String firstname = null; String lastname = null; String login = null; String profile = null; List site_id = new ArrayList(); String validation_status = null; JSONObject responseJson = new JSONObject(); Map expressionAttributeValues = new HashMap(); String filterExpression = ""; String RegionAWS = REGION.toString(); client = AmazonDynamoDBClientBuilder.standard().withRegion(RegionAWS).build(); DynamoDB dynamoDB = new DynamoDB(client); Table table = dynamoDB.getTable("LI_user"); try < JSONParser parser = new JSONParser(); JSONObject event = (JSONObject) parser.parse(reader); logger.log(event.toJSONString()); if (event.get("body") != null) < JSONObject bod = (JSONObject)parser.parse((String)event.get("body")); // JSONObject bod = (JSONObject) event.get("body"); if ( bod.get("id") != null) < user_id = (Number)bod.get("id"); >if ( bod.get("birthdate") != null) < birthdate = (String)bod.get("birthdate"); >if ( bod.get("email") != null) < email = (String) bod.get("email"); >if ( bod.get("employment_status") != null) < employment_status = (String) bod.get("employment_status"); >if ( bod.get("firstname") != null) < firstname = (String) bod.get("firstname"); >if ( bod.get("lastname") != null) < lastname = (String) bod.get("lastname"); >if ( bod.get("login") != null) < login = (String) bod.get("login"); >if ( bod.get("profile") != null) < profile = (String) bod.get("profile"); >if ( bod.get("validation_status") != null) < validation_status = (String) bod.get("validation_status"); >> 

Источник

json.simple cant cast String to JSONObject error

Does anyone know why? Thanks in advance for any reply. EDIT: So I made the old code work somehow, here’s how it looks now:

 JSONParser jsonParser = new JSONParser(); JSONArray jsonArray = (JSONArray) jsonParser.parse(new FileReader("plugins/LogicGates/ands.json")); Iterator i = jsonArray.iterator(); while (i.hasNext())
Unexpected character (C) at position 8. 
 FileWriter writer = new FileWriter("plugins/LogicGates/ands.json"); JSONArray jsonArray = new JSONArray(); JSONObject obj = new JSONObject(); for(And a : ands) < obj.put("Gate", a.getGate()); obj.put("Inp1", a.getInp1()); obj.put("Inp2", a.getInp2()); jsonArray.add(obj.toJSONString()); >writer.write(jsonArray.toJSONString()); writer.close(); 

Ok, so i fixed the reading error with some parsing, but now i have a completely different error: Unexpected character (C) at position 8.

Can you edit your question to include this new information, instead of using comments? Small point, but it is generally easier to read, that way. And thank you for the updates!

1 Answer 1

I wrote this example before you updated your post.

I assumed you were probably using GSON . but you haven’t told us exactly which library you’re using, nor given an example of your file format.

Anyway, I hope this SSCCE helps:

HelloGson.java

package com.example.hellogson; import java.io.FileReader; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; /** * Illustrates one way to use GSON library to parse a JSON file * * EXAMPLE OUTPUT: * Author: Stephen King, title: The Shining * Author: Larry Niven, title: Ringworld * Author: Robert Heinlein, title: The Moon is a Harsh Mistress * Done parsing test.json */ public class HelloGson < public static final String FILENAME = "test.json"; public static void main(String[] args ) < try < // Open file FileReader reader = new FileReader(FILENAME); // Parse as JSON. // Typically, the toplevel element will be an "object" (e.g."books[]" array JsonParser jsonParser = new JsonParser(); JsonElement rootElement = jsonParser.parse(reader); if (!rootElement.isJsonObject()) < throw new Exception("Root element is not a JSON object!"); >// OK: Get "books". Let's assume it's an array - we'll get an exception if it isn't. JsonArray books = ((JsonObject)rootElement).get("books").getAsJsonArray(); for (JsonElement book : books) < // Let's also assume each element has an "author" and a "title" JsonObject objBook = (JsonObject)book; String title = objBook.get("title").getAsString(); String author = objBook.get("author").getAsString(); System.out.println("Author: " + author + ", title: " + title); >System.out.println("Done parsing " + FILENAME); > catch (Exception e) < System.out.println("EXCEPTION: " + e.getMessage()); e.printStackTrace(); >> > 
  • Perhaps a better approach, rather than mapping individual JSON elements, is to map your entire JSON data structure to Java objects. GSON supports this; Jackson is another commonly used Java library.
  • In the future, please consider writing a «small self-contained example» (an SSCCE like the above. It’s a great way to more quickly get you a better, more accurate answer.
  • Finally, NO library is going to help you if your JSON isn’t well-formed. There are many on-line validation checkers. For example: https://jsonlint.com/

‘Hope that helps — now, and in the future.

Источник

Can’t get value from JSONObject

So I am using the simple json library to perform some json operations. Right now I can construct a JSONObject from a json string but I am not able to get the value from the object I created. For example if I do something like:

String value = (String) jsonRecord.get("Key"); 
java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to java.lang.String 

I removed the type cast to string and it works in IntelliJ. However, when I do this at command line it gives me an error saying:

error: incompatible types: Object cannot be converted to String 
java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray 

@JBNizet Yep, I have read the error message, I think it claims the object returned by the get method can not be cast to a string which does not make sense to me. I can print the value using system.out.println so in theory I should be able to cast it to a string.

4 Answers 4

Your value is a JSONObject, not a string. Your error message makes that quite clear. If you really want it as a string, use

String value = jsonRecord.get("Key").toString(); 

You can pass any object to System.out.println, not just strings, but to actually turn it to a string, you need to call toString() yourself.

However, if you’re expecting an actual String as the Key , and not a JSONObject, then you should take a second look at your JSON, because you’re doing something wrong.

Okay, looking at your schema, I see the problem. Instead of mapping the keys to values directly, your JSON maps keys to objects which then contain values. So to get the array in the JSON you posted, instead of

value = jsonRecord.get("myArray") 
JSONArray value = jsonRecord.getJSONObject("myArray").getJSONArray("array"); 

and for the string, you would use

String value = jsonRecord.getJSONObject("Item").getString("string"); 

Источник

java.lang.ClassCastException: org.json.JSONObject$Null cannot be cast to java.lang.String

Exception is java.lang.ClassCastException : org.json.JSONObject$Null cannot be cast to java.lang.String Printthis>>>>>>userName=user1&passKey=12345678 POST Response Code :: 200 jsonObj>>>>>>>>>>>>>>>>>><"response":,"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) Here is my postLogin code

@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 PatentLoginInfoArray = new ArrayList(); 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; >> 

Источник

Оцените статью