java - 如何将 URL 中存在的 JSON 数据转换为 java 或 android 中的 JSON 字符串?

标签 java android json

我在下面的 android 中尝试了代码:-

        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpGet httpGet = new HttpGet("http://echo.jsontest.com/key/value/one/two");
        String text = null;


        try {
            HttpResponse response = httpClient.execute(httpGet, localContext);

            HttpEntity entity = response.getEntity();

            text = getASCIIContentFromEntity(entity);
            JSONArray jsonObj = new JSONArray(entity);
            System.out.print("message is"+jsonObj);
           }
        catch (Exception e) {
            return e.getLocalizedMessage();
        }
        return text;

        //Below i am displaying in my layout in my emulator

        protected void onPostExecute(String results) {
         if (results!=null) {
            TextView et = (TextView)findViewById(R.id.data);
            et.setText(results);
         }

         Button b = (Button)findViewById(R.id.getvehicles);
         b.setClickable(true);
       }

所以当我只使用 getASCIIContentFromEntity(entity) 时,我就能够按原样打印完整的 JSON 数据。但是我只想打印此 URL 中的值 it is JSON data,please open to see it .

我如何获取此 json URL 中的值?

最佳答案

您的响应采用 JSONObject 形式,因此您必须像这样获取它。

HttpResponse response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
Object content = EntityUtils.toString(entity);
JSONObject jsonObj = new JSONObject(content.toString());

System.out.print("message is"+jsonObj.toString()); 

然后你的 JSONObject 包含多个值,你可以使用对的“键”来获取它。

String value = jsonObj.getString(key); //String value = jsonObj.getString("one");

在您的情况下,您想要打印一和二,这意味着 kay 和值,因此您必须像这样迭代整个集合(如果您知道响应中使用的键,则无需使用此方法)。

Iterator<?> keys = jsonObj.keys();

     while( keys.hasNext() ){
          String key = (String)keys.next();
          System.out.print("key - value"+ key +   jsonObj.getString(key)); 
    }

关于java - 如何将 URL 中存在的 JSON 数据转换为 java 或 android 中的 JSON 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28761834/

相关文章:

java - 以字节数组形式上传到服务器的图像损坏(图像无法打开)

java - Android:无法从扩展Thread的类中调用新 Activity

android - Android Studio中带有Gradle的参数的方法

python - 将字典中的键和值打印到 html 表(以某种格式) JSON 调用

java - 如何在 Groovy 中显示多字节字符?

java - Dockerfile 无法复制指定的本地目录和文件

java - Android 中如何检测物理按键的双击?(onKeyMultiple)

java - 如何在运行时更改日志级别而不重新启动 Vert.x 应用程序

java - onDestroy() 方法上出现 NullPointerException

php - 从 mysql 查询返回额外的项目