如何按顺序获得json响应

时间:2012-05-15 05:44:10

标签: android json

我需要按照浏览器中的显示顺序获取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 "";
}

1 个答案:

答案 0 :(得分: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;

}