1

我对json有问题。我从服务器得到这个响应:

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

如何将此数据保存在数组或其他内容中以具有架构:键 - 值?

4

4 回答 4

4

嗯,不知道我明白你为什么想要这个。一个JSONObject给你正是这样,看看JSONObject.get()

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

不过,如果您想遍历所有值,您可以这样做:

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!
    }   
}
于 2013-06-17T10:27:56.550 回答
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 );
}

解决方案,或多或少。//编写时未检查 IDE,因此可能包含错误/错误

于 2013-06-17T10:27:50.237 回答
0
JSONObject json = new JSONObject(response);
json.getInt(keyA);
json.getString(keyB);

等等;

于 2013-06-17T10:30:42.980 回答
0

您可以将此函数与 httpResponse 一起使用是您的 json 字符串:

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;
}
于 2013-06-17T10:34:57.493 回答