String cannot be cast to org.JSONObject - java

I have this piece of code that was working and all of a sudden is now throwing a Cast Exception. Have anyone experienced something similar? Thanks.
#Override
public List<RecordJSONclass> handleResponse(HttpResponse response)
throws IOException {
List<RecordJSONclass> result = new ArrayList<RecordJSONclass>();
String JSONResponse = new BasicResponseHandler().handleResponse(response);
try {
JSONObject object = (JSONObject) new JSONTokener(JSONResponse).nextValue();
JSONObject earthquakes = object.getJSONObject("data");
JSONArray temp = earthquakes.getJSONArray("temperature");
JSONArray prob = earthquakes.getJSONArray("pop");
is throwing a
java.lang.ClassCastException: java.lang.String cannot be cast to
org.json.JSONObject
at myxmlparser.ResponseHandlerJSON.handleResponse(ResponseHandlerJSON.java:22)
The exception happens at line
JSONObject object = (JSONObject) new
JSONTokener(JSONResponse).nextValue();
however a String is passed as example in the Class overview in http://developer.android.com/reference/org/json/JSONTokener.html

Well, it is the return value. The nextValue method does not return a JSONObject. It returns a String in this case.
From the Javadoc:
Object nextValue() - Returns the next value from the input.
So, you can't assume that it is a JSONObject.
So, to get hold of the correct value simply use:
String val = (String) new JSONTokener(JSONResponse).nextValue();

Related

The type of the expression must be an array type but it resolved to JSONArray

I am getting an JSON object then converting it into array and trying to access the properties or values, but getting error as The type of the expression must be an array type but it resolved to JSONArray
I have to save the JSON data into my Database thats why I am getting all to values in array
My code
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Scanner scanner = new Scanner(request.getInputStream());
String imageData = scanner.nextLine();
System.out.println(imageData);
JSONObject jsonObj = new JSONObject(imageData);
JSONArray jsonArray = jsonObj.getJSONArray("ImageData");
JSONObject innerObj = new JSONObject(jsonArray[0]); // this one is throwing error
// eror is `The type of the expression must be an array type but it resolved to JSONArray`
String counter = innerObj.getString("Counter");
String name = innerObj.getString("Name");
String isActive = innerObj.getString("IsActive");
System.out.println(counter);
}
System.out.println(imageData); it prints -->
{"ImageData":[{"Counter":"Counter A","Name":"CountA1.jpg","IsActive":"Y"},{"Counter":"Counter A","Name":"CountA2.jpg","IsActive":"Y"}]}
System.out.println(jsonArray); This one prints -->
[{"Counter":"Counter A","IsActive":"Y","Name":"CountA1.jpg"},{"Counter":"Counter A","IsActive":"Y","Name":"CountA2.jpg"}]
I have commented the line in my code where I am getting error
Use getJSONObject method
JSONObject innerObj = jsonArray.getJSONObject(0);
Returns the value at index if it exists and is a JSONObject.
You can't add square brackets to JSONArray like jsonArray[0], You have to use jsonArray.getJSONObject("index");

How to sum up two json values in java android?

Can any one tell me, how to sum two JSON objects values? Say, for an example:
First JSON
{
"json_obj":20,
}
Second JSON
{
"json_obj":40,
}
Here what I wanted is, I'm trying to create one JSON as same as like the above one, but i need to sum up two values of the JSON object "json_obj" and finally need to show it as like the below JSON
Resultant JSON
{
"json_obj":60
}
How to achieve this?
Try this,
JSONObject jsonObject1 = new JSONObject(First_JSON);
JSONObject jsonObject2 = new JSONObject(Socond_JSON);
JSONObject jsonObject3 = new JSONObject();
jsonObject3.put("json_obj", jsonObject1.getInt("json_obj")+jsonObject2.getInt("json_obj"));
Try this:
public String getAddedValues(String firstJson, String secondJson, String key){
JSONObject first = new JSONObject(firstJson);
JSONObject second = new JSONObject(secondJson);
int value = first.getInt(key) + second.getInt(key);
JSONObject output = new JSONObject();
output.put(key, value);
return output.toString();
}
Invoke it passing your json Strings and the "json_obj" String as key.
The idea is that you forst need to convert the json string into a Java object. Then you do your calculations, and finally you create another JSONObject with the result. JSONObject.toString() returns the common String representation you would expect as output :-)
You can try something like that:
public class CalcObj {
public int json_obj;
}
public String sumTwoJsons(String json1, String json2) {
Gson _gson = new Gson();
CalcObj obj1 = _gson.fromJson(json1, CalcObj.class);
CalcObj obj2 = _gson.fromJson(json2, CalcObj.class);
CalcObj objSum = new CalcObj();
objSum.json_obj = obj1.json_obj + obj2.json_obj;
return _gson.toJson(objSum );
}

JSON-simple get JSONObject using method

I have been working on a project that requires JSON for getting data from a large json file, but I ran into a problem when trying to get a json string using a method.
the method for getting the ID works I have tested this multiple times. When I enter int he ID as a string it also works prefectly but when I use the method to get the jsonString it stops working and gives a nullpoiterexeption
public static int getLvlMin(ItemStack is) throws ParseException {
String id = getID(is);
system.out.println(id);
JSONParser parser = new JSONParser();
Object obj = parser.parse(Main.weapons);
JSONObject jsonObj = (JSONObject) obj;
system.out.printlnjsonObj.toJSONString());
JSONObject weapon = (JSONObject) jsonObj.get(String.valueOf(getID(is)));
system.out.println(weapon.toJSONString());
return 1;
}
This is the json string I am trying to get info {"W1121000-00002":{"clnt":1023,"srvr":870}} and I am trying to get the clnt value out of that string.

Exception while parsing JSON data

I am parsing JSON data from this link:
http://twyst.in/api/v1/near/30/30
As the data is too large, I am posting only the (problem) relevant data here:
{
"info": "[{\"outlet\":{\"__v\":1,\"_id\":\"5316d59326b019ee59000026\",\"photos\":[],\"twyst_meta\":{\"recommend_list\":[],\"reviews\":[]},\"outlet_meta\":{\"links\":[],\"status\":\"active\",\"accounts\":[\"531574eeae738d654c00000a\",\"535a1a1e827651ca03000122\"]},\"attributes\":{\"dine_in\":true,\"outdoor\":true,\"air_conditioning\":\"Not Available\",\"parking\":\"Available\",\"reservation\":\"Not Required\",\"wifi\":\"Not Available\",\"tags\":[\"Pizza\",\"Pasta\",\"Italian\",\"Galleria\",\"DLF Phase 4\"],\"payment_options\":[\"cash\",\"amex\",\"visa\",\"master\"],\"cuisines\":[\"Italian\",\"Pizza\",\"Gelato\"],\"timings\":\"11 AM - 11 PM\",\"cost_for_two\":{\"min\":3,\"max\":4}},\"links\":{\"other_urls\":[],\"youtube_url\":\"\",\"twitter_url\":\"\",\"facebook_url\":\"https://www.facebook.com/pages/Crusty-gourmet-pizza-more/390843954384130\",\"website_url\":\"\"},\"contact\":{\"emails\":{\"email\":\"bob_nugent56#yahoo.com\",\"person\":\"\"},\"phones\":{\"number\":\"\",\"landline\":\"02355156616\",\"reg_mobile\":[{\"_id\":\"4639320000e4532779b17de7\",\"num\":\"9134000410\"}
This is not the end of JSON data, it goes on...
But when the following line of code is executed, I am getting a JSONException. The e.printStackTrace() method tells me that there is typeMismatch error.
JSONObject object = new JSONObject(str); //1
JSONArray array = object.getJSONArray("info"); //2
I have tried replacing the line 2 with the following code:
JSONObject newObject = object.getJSONObject("info");
But here also I encountered the same problem.
I have checked the complete data, it is correct, no syntax error.
Can anybody help me with the issue ? Can the presence of double quotes before starting of JSONArray be the root of this problem ?
Thanks.
info is not an array or an object. It's a string, which just happens to contain the JSON-encoded representation of another array. You will have to get that string and run it through a second JSON decoding pass:
JSONArray array = new JSONArray(object.getString("info"));
JSONObject json;
Object info;
JSONArray infoJsonArray;
JSONObject infoObject;
json = new JSONObject(str);
Object info= json.get("info");
if (info instanceof JSONArray) {
// It's an array
infoJsonArray = (JSONArray)info;
}
else if (info instanceof JSONObject) {
// It's an object
infoObject = (JSONObject)info;
} else {
// It's something else, like a string or number
}

JSON Object is null while parsing

The format of my json object is:
String jsonObjRecv = {
"response":{
"respobj":{
"id":<int>,
"number":<string>,
"validated":<boolean>
}
},
"status":"ok",
"errors":null
}
It works when code is:
JSONObject jsonObjCont = new JSONObject(jsonObjRecv);
String getString= jsonObjCont.toString(2);
In this case getString != null and I can receive data, but when I try to get nested data of JSON object as like:
JSONObject jsonObjCont = new JSONObject(jsonObjRecv);
JSONObject regNumber = jsonObjCont.getJSONObject("respobj");
String number= regNumber.getString("number");
it dont work.
I tried to use GSON library, but it works when:
public String parse(String jsonObjRecv) {
JsonElement jelement = new JsonParser().parse(jsonObjRecv);
String result = jelement.toString();
return result;
and don't work :
public String parse(String jsonObjRecv) {
JsonElement jelement = new JsonParser().parse(jsonObjRecv);
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject("respobj");
String result = jobject.get("number").toString();
return result;
Where is my mistake?
The problem is you're not accessing your JSON object correctly - it's an object that contains a response object which contains a respobj object.
Gson example follows. Note the comment in the code - you need to get the response object then get the respobj from it.
public static void main( String[] args )
{
String jsonObjRecv = "{\"response\":{\"respobj\":{\"id\":1,\"number\":\"22\",\"validated\":true}},\"status\":\"ok\",\"errors\":null}";
JsonElement jelement = new JsonParser().parse(jsonObjRecv);
JsonObject jobject = jelement.getAsJsonObject();
// Here is where you're making an error. You need to get the outer
// 'response' object first, then get 'respobj' from that.
jobject = jobject.getAsJsonObject("response").getAsJsonObject("respobj");
String result = jobject.get("number").getAsString();
System.out.println(result);
}
Output:
22
Edit to add: Note I used getAsString() vs. toString() - if you use the latter you get the raw JSON which will incluse the quotes around the value (e.g. the output would be "22")

Categories