1

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?

3
  • you want a class tha holds those values ? Commented Jun 17, 2013 at 10:26
  • no, I want array or something else to for example: for key TESTS I want to get value true. Commented Jun 17, 2013 at 10:28
  • 1
    but if you have one object why do you need an array? Commented Jun 17, 2013 at 10:29

4 Answers 4

4

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!
    }   
}
Sign up to request clarification or add additional context in comments.

Comments

2
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

Comments

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

and etc;

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.