Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get json from HttpResponse

Tags:

java

json

android

People also ask

How do I get HTTP response as JSON?

To return JSON from the server, you must include the JSON data in the body of the HTTP response message and provide a "Content-Type: application/json" response header. The Content-Type response header allows the client to interpret the data in the response body correctly.

How do I request JSON data?

To request JSON from a URL, you need to send an HTTP GET request to the server and provide the Accept: application/json request header with your request. The Accept header tells the server that our client is expecting JSON.

How do I get response body from Org Apache Httpresponse?

To get the response body as a string we can use the EntityUtils. toString() method. This method read the content of an HttpEntity object content and return it as a string. The content will be converted using the character set from the entity object.

How do I parse JSON in Rest assured?

We can parse JSON Response with Rest Assured. To parse a JSON body, we shall use the JSONPath class and utilize the methods of this class to obtain the value of a specific attribute. We shall first send a GET request via Postman on a mock API URL and observe the Response body.


I think the problem you are running into is one similar to my own I just ran into. If you run:

String json_string = EntityUtils.toString(response.getEntity());
JSONObject temp1 = new JSONObject(json_string);

The above code will throw an exception and it looks like the JSON array brackets are to blame. But it's fine to have a JSON array as the top level element! You just need to use JSONArray() instead of JSONObject:

String json_string = EntityUtils.toString(response.getEntity());
JSONArray temp1 = new JSONArray(json_string);

So you have to know if you are getting a JSONArray or a single dictionary that is a JSONObject in your JSON code.

If you are used to the iOS/Objective-C JSON parsing libraries they use the same top level element to deal with json dictionaries and json array's, so moving to the JAVA / Android world confused me about having two types for handling JSON depending on the top level returned.


With this class, you can get the JSON data from either from a server or from your assets folder. It can be easily changed to only one or the other. If you need a Adapter use the one jgilfelt created here on getHub.

@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        Bundle getArgs = this.getArguments();
        String URI = getArgs.getString(KEY_URI);//OR YOU CAN HARD CODE THIS OR GET THE STRING ANYWAY YOU LIKE.

        new GetJSONTask().execute(URI);
    }

    class GetJSONTask extends AsyncTask<String, Integer, String> {

        protected String doInBackground(String... arg0) {

            String uri = arg0[0];

            InputStream is = null;

            if (uri.contains("http") == true) {// Get JSON from URL
                try {
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(uri);
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();

                    BufferedReader rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    while ((line = rd.readLine()) != null) {
                        json += line;
                    }
                    rd.close();
                    return json;
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
            } else {// Get JSON from Assets

                Writer writer = new StringWriter();
                char[] buffer = new char[1024];

                try {
                    InputStream jsonFile = getActivity().getAssets().open(uri);
                    Reader reader = new BufferedReader(new InputStreamReader(jsonFile, "UTF-8"));
                    int n;
                    while ((n = reader.read(buffer)) != -1) {
                        writer.write(buffer, 0, n);
                    }
                    jsonFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                json = writer.toString();
                // return JSON String
                return json;
            }
        }

        @Override
        protected void onPostExecute(String result) {
            try {
                showData(result);
            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(getActivity(), "something went wrong", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void showData(String json) throws JSONException {
        JSONObject o = new JSONObject(json);
        JSONArray data = o.getJSONArray("results");
    }
}

The problem was in my php file. Removing the container array from the json encoded object made my java code work.