【问题标题】:How to parse the Json response in android?如何在android中解析Json响应?
【发布时间】:2013-01-26 13:54:24
【问题描述】:

我在对服务器的 GET 请求的结果中收到此响应

{"LL": { "control": "dev/sys/getkey", "value": "4545453030304138303046392035343733373432363020323031332D30322D31312031383A30313A3135", "Code": "200"}}

我只想从上面的json响应中提取"value"的值。

我正在使用此代码来获取此响应

findViewById(R.id.button1).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            HttpResponse response = null;
            try {
                HttpClient client = new DefaultHttpClient();
                HttpGet request = new HttpGet();
                request.setURI(new URI(
                        "http://192.168.14.247/jdev/sys/getkey"));
                response = client.execute(request);
            } catch (URISyntaxException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            String responseText = null;
            try {
                responseText = EntityUtils.toString(response.getEntity());
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.i("Parse Exception", e + "");

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.i("IO Exception 2", e + "");

            }

            Log.i("responseText", responseText);

            Toast.makeText(MainActivity.this, responseText + "",
                    Toast.LENGTH_SHORT).show();

        }

    });

我的问题是我如何解析这个并仅获取 "value" 标记的值。 谢谢

【问题讨论】:

    标签: android json parsing


    【解决方案1】:

    您可以解析当前的 json 字符串以从中获取value

    // Convert String to json object
    JSONObject json = new JSONObject(responseText);
    
    // get LL json object
    JSONObject json_LL = json.getJSONObject("LL");
    
    // get value from LL Json Object
    String str_value=json_LL.getString("value"); //<< get value here
    

    【讨论】:

    • @QadirHussain:意思是我没有得到你。是的,你正在从服务器获取 json 字符串
    【解决方案2】:

    试试这个,

    JSONObject ResponseObject = new JSONObject(Response);
    String str = ResponseObject.getJSONObject("LL").getString(value);
    

    【讨论】:

    • 感谢您的帮助.. 我想再问一个。这是我得到的 Json 响应吗?并解析
    • 与@ρяσѕρєяK 的回答有何不同?
    【解决方案3】:

    试试这个:

    JSONObject json= json1.getJSONObject("LL");    
    
    String value= json.getString("value");
    

    【讨论】:

    • 我无法在问题提供的当前 json 字符串中找到任何 Json 数组?
    • LL 不是 jsonArray,它是 jsonObject
    • 与@ρяσѕρєяK 的回答有何不同?
    【解决方案4】:

    试试这个

    JSONObject json = (JSONObject) JSONSerializer.toJSON(responseText);   
    String value = json.getJSONObject("LL").getString("value");
    

    【讨论】:

      【解决方案5】:

      您可以解析您的响应并获得价值试试这个:

      try {
        JSONObject jsonObject = new JSONObject(response);// Convert response string in to json object.
      
        JSONObject jsonLL = jsonObject.getJSONObject("LL");// Get LL json object from jsonObject.
      
        String strValue = jsonLL.getString("value");// Get value from jsonLL Object.
      
         } catch (Exception e) {
          e.printStackTrace();
         }
      

      【讨论】:

        【解决方案6】:

        简单高效解决方案:使用谷歌的Gson库

        • 把它放在 build.gradle 文件中: implementation 'com.google.code.gson:gson:2.6.2'
        • 现在像这样在 2 行中将 JSON 字符串转换为方便的数据结构,例如 HashMap。

        Type type = new TypeToken<Map<String, String>>(){}.getType();
        Map<String, String> myMap = gson.fromJson(JsonString , type);
        

        或者你可以使用下面的类:

        要将您的 JSON 字符串转换为 hashmap,请使用:

        HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(response)) ;
        

        使用这个类 :)(处理偶数列表、嵌套列表和 json)

        public class Utility {
        
            public static Map<String, Object> jsonToMap(Object json) throws JSONException {
        
                if(json instanceof JSONObject)
                    return _jsonToMap_((JSONObject)json) ;
        
                else if (json instanceof String)
                {
                    JSONObject jsonObject = new JSONObject((String)json) ;
                    return _jsonToMap_(jsonObject) ;
                }
                return null ;
            }
        
        
           private static Map<String, Object> _jsonToMap_(JSONObject json) throws JSONException {
                Map<String, Object> retMap = new HashMap<String, Object>();
        
                if(json != JSONObject.NULL) {
                    retMap = toMap(json);
                }
                return retMap;
            }
        
        
            private static Map<String, Object> toMap(JSONObject object) throws JSONException {
                Map<String, Object> map = new HashMap<String, Object>();
        
                Iterator<String> keysItr = object.keys();
                while(keysItr.hasNext()) {
                    String key = keysItr.next();
                    Object value = object.get(key);
        
                    if(value instanceof JSONArray) {
                        value = toList((JSONArray) value);
                    }
        
                    else if(value instanceof JSONObject) {
                        value = toMap((JSONObject) value);
                    }
                    map.put(key, value);
                }
                return map;
            }
        
        
            public static List<Object> toList(JSONArray array) throws JSONException {
                List<Object> list = new ArrayList<Object>();
                for(int i = 0; i < array.length(); i++) {
                    Object value = array.get(i);
                    if(value instanceof JSONArray) {
                        value = toList((JSONArray) value);
                    }
        
                    else if(value instanceof JSONObject) {
                        value = toMap((JSONObject) value);
                    }
                    list.add(value);
                }
                return list;
            }
        }
        

        稍后谢谢我:)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多