Android Studio + JSON getting values


Android Studio + JSON getting values

我已经找了很长时间了,但仍然找不到。

我有JSONObject obj = new JSONObject(result)的解决方案,但我不能使用它,在那里得到一个未处理的JSON异常

所以,我得到了:

[{"NAME":"test"},{"NAME":"John"}]

此JSON位可以扩展。

我在代码中得到的内容:首先,我从.php表单.中获取数据

    public class Download extends AsyncTask<Void, Void, String> {
    @Override
    protected String doInBackground(Void... params) {
        String out = null;
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            final HttpParams httpParameters = httpClient.getParams();
            HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
            HttpConnectionParams.setSoTimeout(httpParameters, 15000);
            HttpGet httpPost = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            out = EntityUtils.toString(httpEntity, HTTP.UTF_8);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return out;
    }
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        showJSON.setText(result);
        Log.e(TAG, result);
        jsonText = result;
    }
}

为了在应用程序中显示代码,我使用Textview:

    private ArrayList<searchResults> GetSearchResults(){
    ArrayList<searchResults> results = new ArrayList<searchResults>();
    searchResults sr1 = new searchResults();
    sr1.setName("test"); //this should be jsonobj.getString("NAME")
    results.add(sr1);
    sr1 = new searchResults();
    sr1.setName("test1"); //This should be jsonobj.getString("NAME")
    results.add(sr1);

    return results;
}

现在:如何从数组中取出测试John部分?然后,由于json可以扩展,我如何使视图(private ArrayList getSearchResults)动态(自动添加新行以获得数组中的更多值)?

我希望这是可读的。请随意编辑!

提前谢谢。

要将JSON字符串转换为对象,我建议使用Gson。

要添加Gson,请将compile 'com.google.code.gson:gson:2.4'添加到build.gradle依赖项中。

SearchResult[] data = new Gson().fromJson(out, SearchResult[].class);

会将字符串转换为搜索结果数组。

然而,我不知道你的动态添加是什么意思,如果转换有效,请尝试更新你的问题。