0

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?

2 Answers 2

4

Try

$array = array("result" => $array);
echo json_encode($array);
Sign up to request clarification or add additional context in comments.

Comments

0

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);
}

Comments

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.