Check string or JSONObject

I need help. If userID is right. JSONObject is

{
  "info": {
    "name": "Guest",
    "age": "18"
  }
}

If userID is wrong. JSONObject is

{
  "info":"wrong"
}

My code:

if (!(resultObject.getString("info").contains("name"))) {
   String strImg = resultObject.getString("info");
   System.out.println("str response: " + strImg);
} else {
   JSONParse jsonParse = new JSONParse();
   JSONObject json = new JSONObject(resultObject.getString("info"));
   onSuccess(jsonParse.convertJsonToInformation(json));
}

But doesn't work. I don't know how to parse it

Answer:1

I suggest you to use a consistent Json format rather than using a dynamic format. So your processing will be always same. You can first check for the status. If the status is "ok" you can then consume the info Json node.

Example for a correct info:

{
  "status": "ok",
  "info": {
    "name": "Guest",
    "age": "18"
  }
}

Example for a wrong info:

{
  "status": "wrong",
  "info": null
}
Answer:2

Solution: You can use optJSONObject and optString method to detect whether the value of a JSON key is a JSON Object or a String.

if(resultObject.optJSONObject("info") != null) {
    // info is a JSON Object.

} else if (resultObject.optString("info") != null) {
    // info is a String.

}
Answer:3

I have an assignment to be done in Java, and I can't figure this out for the life of me. I'm supposed to use Graphics2D and Java.AWT. to mirror an image across both the x-axis and y-axis. Current ...

Ok, I have methods like CompletableFuture fetchCar(int id); CompletableFuture runSomething(Something t, Extra d); CompletableFuture invoke(); and I would like a single method that I can use that ...

Making a runnable .jar with dependent libraries for dummys.. Can someone outline the steps I have to take to making a runnable .jar with dependent libraries for dummy with Maven and Eclipse. I want ...

When I compile a ruby file to a java class using jrubyc, I get different output when compiling with just jrubyc and with jrubyc --java (to generate the java file) and just javac. Why? Example: First ...