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

vlio20
  • 8,955
  • 18
  • 95
  • 180

1 Answers1

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.

Community
  • 1
  • 1
Scott
  • 1,652
  • 1
  • 13
  • 10
  • `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! – vlio20 Jun 17 '13 at 04:29