简体   繁体   English

如何解析android中的Json响应?

[英]How to parse the Json response in android?

im getting this response in a result of GET request to server 我在服务器的GET请求结果中获得此响应

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

i just want to extract the value of "value" from the above json response. 我只想从上面的json响应中提取“value "value"

I m using this code to get this response 我使用此代码来获得此响应

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();

        }

    });

my question is that how can i parse this and get the value of only "value" tag. 我的问题是,我如何解析这个并获得仅"value"标签的"value" thanks 谢谢

you can parse current json String to get value from it as : 你可以解析当前的json String来从中获取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

Try this: 试试这个:

JSONObject json= json1.getJSONObject("LL");    

String value= json.getString("value");

try this 试试这个

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

Try this, 试试这个,

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

You can parse your response and get value try this: 你可以解析你的回复并获得价值试试这个:

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();
   }

Simple and Efficient solution : Use Googlle's Gson library 简单高效的解决方案:使用Googlle的Gson库

  • Put this in build.gradle file : implementation 'com.google.code.gson:gson:2.6.2' 把它放在build.gradle文件中: implementation 'com.google.code.gson:gson:2.6.2'
  • Now convert the JSON String to a convenient datastrucutre like HashMap in 2 lines like this. 现在转换成JSON字符串像HashMap中的方便datastrucutre在2号线这样的。

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

or you can use this below class : 或者您可以使用以下课程:

To convert your JSON string to hashmap use this : 要将JSON字符串转换为hashmap,请使用以下命令:

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

Use this class :) (handles even lists , nested lists and json) 使用此类:) (处理偶数列表,嵌套列表和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;
    }
}

Thank me later :) 晚点再谢我 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM