user2054833
user2054833

Reputation: 2165

Return JSON Object instead of JSONArray

I am writing an android app which interacts with a web-services to get data. The Web-service are writing in PHP and I wrote a Library that uses a AsyncTask to fetch the data the problem is that class only accepts a JSONObject. Most of my services return just a JSONObject by there is particular one that return an json array.

    $array = array();
    while ($row = mysql_fetch_array($query))
    {
        $array[] = $row;
    }
    echo json_encode($array); 

which returns something like this:

 [{ "0":"10","id":"10","1":"17.9409915","lat":"17.9409915","2":"-77.1003625","lon":"-77.1003625"},{"0":"9","id":"9","1":"17.9410143","lat":"17.9410143","2":"-77.1003672","lon":"-77.1003672"}]

What I want to return is

      {result:[{"0":"10","id":"10","1":"17.9409915","lat":"17.9409915","2":"-77.1003625","lon":"-77.1003625"},{"0":"9","id":"9","1":"17.9410143","lat":"17.9410143","2":"-77.1003672","lon":"-77.1003672"}]}

I tried to accomplish this by doing:

  echo json_encode("{result: " .$array. "}");

But that doesn't work. it returns.

 "{result: Array}"

How can I accomplish this?

Upvotes: 0

Views: 545

Answers (2)

user2355549
user2355549

Reputation:

You could also use JSONTokener to dispatch your response to the right handler.

public void dispatchResponse(String response) {
    JSONTokener tokener = new JSONTokener(response);

    try {
        Object object = tokener.nextValue();

        if (object instanceof JSONObject) {
            success(new JSONObject(response));
        } else if (object instanceof JSONArray) {
            success(new JSONArray(response));
        } else {
            // Etc...
        }
    } catch (JSONException e) {
        Log.d("debug", "JSONException: "+ e.getMessage());
    }
}

public void success(JSONObject response) {
    Log.d("debug", "JSONObject: "+ response);
}

public void success(JSONArray response) {
    Log.d("debug", "JSONArray: "+ response);
}

Upvotes: 0

Zwirbelbart
Zwirbelbart

Reputation: 827

Try

$array = array("result" => $array);
echo json_encode($array);

Upvotes: 4

Related Questions