-3

我需要按照浏览器中显示的正确顺序获取 json 对象响应,但它是随机的。这是我的 Post 函数,用于获取客户端的响应。我也想通过迭代器而不是字符串来获取所有 Array 字段

jsonserch2.getString("@id");

我使用 Iterator myVeryOwnIterator=jsonserch2.keys() 填充迭代器

String response = postData("http://url",generateRequestJson(this));


public static String postData(String url, String json) {
    final HttpClient httpclient = new DefaultHttpClient();
    final HttpPost httppost = new HttpPost(url);
    httppost.setHeader("Content-type", "application/x-www-form-urlencoded");

    final ArrayList<NameValuePair> values = new ArrayList<NameValuePair>();
    values.add(new BasicNameValuePair("data", json));
    String response = "";
    try {
        httppost.setEntity(new UrlEncodedFormEntity(values));
        final HttpResponse httpResponse = httpclient.execute(httppost);
        response = convertInputStreamToString(httpResponse);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return response;
}

private static String convertInputStreamToString(HttpResponse response) {
    BufferedReader bufferedReader = null;
    try {
        bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        // JsonReader reader = new JsonReader(new
        // InputStreamReader(response.getEntity().getContent()));
        // Log.e("",""+reader);
        final StringBuffer stringBuffer = new StringBuffer("");
        String line = "";
        final String LineSeparator = System.getProperty("line.separator");
        //

        //
        while ((line = bufferedReader.readLine()) != null) {
            stringBuffer.append(line + LineSeparator);
        }
        return stringBuffer.toString();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return "";
}
4

1 回答 1

0

试试这个

 public void getJsonData() {
      InputStream source = retrieveStream(url);     
      Gson gson = new Gson();      
      Reader reader = new InputStreamReader(source);      
      jsonPlots response = gson.fromJson(reader, jsonPlots.class);
      Toast.makeText(this, response.mFieldId, Toast.LENGTH_SHORT).show();  // this works
    ArrayList<Plants> results = response.PlantArray;

}  
于 2012-05-15T06:59:50.800 回答