I am getting response from JSON in two format String and Array, so am not able to handle it becuase i am not sure which format will be
Is there any way to handle string and array type response using java
Kindly let me know thanks in advance
I am getting response from JSON in two format String and Array, so am not able to handle it becuase i am not sure which format will be
Is there any way to handle string and array type response using java
Kindly let me know thanks in advance
I think you can use try catch exception in this case. First, try to treat the response as String. if it occurs error, just catch error and treat the response as Array.
Just check the datatype of JSON's message
part and accordingly use that.
Check out this example.
package test;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class jsonDeco {
public static void main(String[] args) throws JSONException {
// TODO Auto-generated method stub
JSONObject a = new JSONObject("{ \"status_code\": 2002, \"sub_status_code\": 2002,"
+ " \"message\": \"Service Invoke Create Step2 Success\"} ");
JSONObject b = new JSONObject("{ \"status_code\": 7000, \"sub_status_code\": 7001,"
+ " \"message\": [ \"Step No: Step 2: Line No: 92 Variable Name: lan-pool-ipv6-mask"
+ " Error Code: 7516 Error Detail: Lan Pool IPV6 network address is invalid Description: \" ]}");
parseAORB(b);
}
public static void parseAORB(JSONObject input) throws JSONException
{
String code = input.getString("status_code");
System.out.println(code);
System.out.println(nameOf(input.get("message")));
if(nameOf(input.get("message")).equals("String"))
{
System.out.println("inside string");
String message = input.getString("message");
System.out.println("Message is : "+message);
}
else if (nameOf(input.get("message")).equals("JSONArray"))
{
JSONArray message = input.getJSONArray("message");
System.out.println("inside jsonarray");
System.out.println("Message is : "+message.getString(0).toString());
}
}
private static String nameOf(Object o) {
return o.getClass().getSimpleName();
}
}
You can pass variable a
or b
to test.
P.S. In the comment, both the example is wrong. In first one, there is one comma ,
extra at the end and in the second example, you didn't close the curly bracket }
.