【问题标题】:Parse http GET response body解析 http GET 响应正文
【发布时间】:2013-05-25 00:35:31
【问题描述】:

我正在连接一个网站及其 api 来检索数据。我下面的代码会执行此操作并获取响应正文,但是如何解析该响应正文? 我是否必须创建自己的函数来搜索我想要的术语,然后获取每个术语的子内容?还是已经有一个我可以使用的库可以为我做到这一点?

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

响应正文

{
"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
    }
  ]
}

【问题讨论】:

    标签: java android apache http


    【解决方案1】:

    该数据格式是 JSON(JavaScript Object Notation)。因此,您只需要一个与 Android 兼容的 JSON 解析器,例如 GSON,就可以开始了。

    【讨论】:

    • 好的,谢谢,这就是 JSON 的样子。我只是打算使用默认的 org.json.JSONObject 并编写我自己的类
    • 改用 GSON 有什么好处?
    【解决方案2】:

    /那是JSON,你可以使用Jackson r Gson之类的库来反序列化它。

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

    您可以将 Java 对象映射到 Json 或像通用对象一样反序列化它。

    【讨论】:

    • 把它变成java对象有什么意义?为什么不直接解析呢?
    【解决方案3】:

    Spring 的RestTemplate 非常简单,它会自动将响应正文直接解组(即解析)为与响应的 JSON 格式匹配的 Java 对象:

    首先,定义您的 Java 类以匹配数据格式,必要时使用 JAXB 注释。这是一个基于您的响应正文的稍微简化的模型:

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

    然后你只需使用 Spring 的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 行代码发出请求并将响应主体作为 Java 对象获取。它并没有变得更简单。

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

    【讨论】:

      【解决方案4】:

      在您的包中添加以下 JSONParser.java 类并使用类似,

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

      【讨论】:

        猜你喜欢
        • 2016-06-20
        • 2015-08-24
        • 2015-07-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-08
        • 2017-12-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多