0

I am trying to pass some simple javascript object from my Parse.com cloud function (back-end)to my android application.

Here is the code of the javascript class:

function Rate()
{
  this.avgRate = 0.0;
  this.numberOfRaters = 0;
}

Here is how I pass it (2 options):

response.success(resp); // {avgRate = 4,numberOfRaters = 1}
response.success(JSON.stringify(resp)); // {"avgRate":4,"numberOfRaters":1}

Here is how I get it in java:

Object test = ParseCloud.callFunction("createNewRate", params); // test is {avgRate = 4,numberOfRaters = 1} or {"avgRate":4,"numberOfRaters":1} (option 1 or 2)
JSONObject response = ParseCloud.callFunction("createNewRate", params); // here is a crash

The error that I get is:

06-16 23:51:44.337: E/AndroidRuntime(13892): Caused by: java.lang.ClassCastException: java.util.HashMap cannot be cast to org.json.JSONObject

How should I handle this correctly?

Thanks

1 Answer 1

1

It seems that ParseCloud.callFunction(...) returns a HashMap not a JSONObject (Did it crash when you set the java variable as Object?). One option is to change the variable type of response from JSONObject to HashMap and then iterate over the map and build the JSONObject manually with the key-value pairs of the map... Here is an example of how to iterate over a hashmap:

Iterate through a HashMap

if it is not necessary to make the JSONObject, you can bypass the JSONObject and use the values as you wish.

Sign up to request clarification or add additional context in comments.

1 Comment

Did it crash when you set the java variable as Object?: nope it is not crashing. It is very strange because when I passing javascript array of Rate objects and catching it with JSONArray than iterating through it and extracting JSONObject every thing works fine. The solution with the HashMap is good but I would like to consistent with my code, Maybe there are things I can do in the javascript (back-end). Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.