简体   繁体   中英

Parse http GET response body

I am connecting with a website and its api to retrieve data. My code below does that and gets the response body, but how do I parse that response body? Will I have to create my own function that will have to search for the terms that I want and then get the subcontents of each term? or is there already a library that I can use that can do that for me?

private class GetResultTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
      String response = "";

        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet("https://api.bob.com/2.0/shelves/45?client_id=no&whitespace=1");
        try {
          HttpResponse execute = client.execute(httpGet);
          InputStream content = execute.getEntity().getContent();

          BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
          String s = "";
          while ((s = buffer.readLine()) != null) {
            response += s;
          }

        } catch (Exception e) {
          e.printStackTrace();
        }

      return response;
    }

    @Override
    protected void onPostExecute(String result) {
      apiStatus.setText(result); //setting the result in an EditText
    }
  }

Response Body

{
"id": 415,
"url": "http://bob.com/45/us-state-capitals-flash-cards/",
"title": "U.S. State Capitals",
"created_by": "bub12",
"term_count": 50,
"created_date": 1144296408,
"modified_date": 1363506943,
"has_images": false,
"subjects": [
    "unitedstates",
    "states",
    "geography",
    "capitals"
],
"visibility": "public",
"has_access": true,
"description": "List of the U.S. states and their capitals",
"has_discussion": true,
"lang_terms": "en",
"lang_definitions": "en",
"creator": {
    "username": "bub12",
    "account_type": "plus",
    "profile_image": "https://jdfkls.dfsldj.jpg"
},
"terms": [
    {
        "id": 15407,
        "term": "Montgomery",
        "definition": "Alabama",
        "image": null
    },
    {
        "id": 15455,
        "term": "Juneau",
        "definition": "Alaska",
        "image": null
    },

    {
        "id": 413281851,
        "term": "Tallahassee",
        "definition": "Florida",
        "image": null
    },
    {
        "id": 413281852,
        "term": "Atlanta",
        "definition": "Georgia",
        "image": null
    }
  ]
}

/That's JSON, you can use a library like Jackson r Gson to deserialize it.

http://jackson.codehaus.org/ http://code.google.com/p/google-gson/

You can map your Java objects to the Json or deserialize it like a generic object.

That data format is JSON (JavaScript Object Notation). So all you need is an android-compatible JSON parser, like GSON , and you're good to go.

Spring's RestTemplate is so simple that it will automatically unmarshal (ie parse) the response body directly into Java objects that match the JSON format of the response:

First, define your Java classes to match the data format, using JAXB annotations if necessary. Here is a somewhat simplified model based on your response body:

@XmlRootElement
class MyResponseData {
    long id;
    String url;
    String title;
    String created_by;
    int term_count;
    int created_date;
    int modified_date;
    boolean has_images;
    List<String> subjects;
    Creator creator;
    List<Term> terms;
}

class Creator {
    String username;
    String account_type;
    String profile_image;
}

class Term {
    long id;
    String term;
    String definition;
    String image;
}

Then you just make the request with Spring's RestTemplate

String url = "https://api.bob.com/2.0/shelves/45?client_id=no&whitespace=1";
RestTemplate template = new RestTemplate();
MyResponseData body = template.getForObject(url, MyResponseData.class);

3 lines of code make the request and get the response body as a Java object. It's doesn't get much simpler.

http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html

Add following JSONParser.java class in your package and use like,

YourClass.java

JSONObject json = jParser.getJSONFromUrl(YOUR_URL_TO_JSON);

try {
        // Getting Array of terms
    JSONArray terms = json.getJSONArray("terms");

    // looping through All Contacts
    for(int i = 0; i < terms.length; i++){

         JSONObject termsJsonObject= terms.getJSONObject(i);

             String id = termsJsonObject.getJSONObject("id").toString();
             String term = termsJsonObject.getJSONObject("term").toString();
             String definition = termsJsonObject.getJSONObject("definition").toString();
             String image = termsJsonObject.getJSONObject("image").toString();

             // do  your operations using these values
         }
  }
  catch (JSONException e) {
        e.printStackTrace();
    return "";
  }

JSONParser.java

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();          

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM