简体   繁体   中英

Save json to array key-value in android

I have a problem with json. I get this response from server:

{"TESTS":true,"TESTS_VIEW":true,"ORDER":true,"PARAMETERS":true,"VIEW":true}

How can I save this data in array or something else to have schema: key - value?

Hmm, not sure I understand why you want this. A JSONObject gives you exactly that, have a look at JSONObject.get() :

JSONObject json = new JSONObject(yourjsonstringfromserver);
boolean tests = json.getBoolean("TESTS");

Still, if you want to iterate over all values you can do like this:

Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keys = json.keys();
for(String key : keys) {
    try {
        Object value = json.get(key);
        map.put(key, value);
    }
    catch (JSONException e) {
        // Something went wrong!
    }   
}
JSONObject object = YourObjectHere;
Map<String,Boolean> dict = new HashMap<String,Boolean>();
Iterator it = object.keyes();

while( it.hasNext() ){
 String key = it.next();
 String value = object.get(key);
 dict.put( key, value );
}

Solution, more or less. //Written without checking in IDE so may contain bugs/errors

JSONObject json = new JSONObject(response);
json.getInt(keyA);
json.getString(keyB);

and etc;

You can using this function with httpResponse is your json string:

public static YourModel parseJson(String httpResponse) {
    YourModel objObject = new YourModel();
    try {
        JSONArray jsonArrayData = new JSONArray(httpResponse);
        if (jsonArrayData.length() >= 1) {
            for (int i = 0; i < jsonArrayData.length(); i++) {
                JSONObject object = new JSONObject(jsonArrayData.get(0));
                // Setting value by key json
                objObject.setAtrr(object.getString("YourKey"));
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
        return null;
    }
    return objObject;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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