首页 > 解决方案 > 如何在Android中设计javaBean

问题描述

我得到像这样的json:

{ 
  "success":[
   {"key":"headache", "value":false},
   {"key":"fatigue", "value":false}, 
   {"key":"sputum,color", "value": [
      "none",
      "green",
      "yellow",
      "white",
      "rustColor",
      "grayBlack"]
   }
  ],
 "errorCode":0}

我尝试解析 json ,因为我需要将键和值放入 RecyclerView。

JSONObject object = new JSONObject(result.toString());
int errorCode = object.getInt("errorCode");
if (errorCode == 0){
    JSONArray array = object.getJSONArray("success");
    for (int i = 0; i < array.length(); i++){
      JSONObject newObject = array.getJSONObject(i);
      String keyStr = newObject.getString("key");
      Object value = newObject.get("value");
      if (value instanceof String){
        String valueString = value.toString();
      else if (value instanceof Boolean)
        Boolean valueBoolean = (Boolean) value;
    }
}

有没有人可以帮助我?

标签: androidjavabeans

解决方案


最好的方法是修复您的 JSON 问题,因为对于不同的值类型使用相同的键是不正确的。

如果你不能,我想你会这样做:

try {
    boolean boolValue = newObject.getBoolean("value");
    // here, you will have a Boolean
} catch (JSONException e) {
    // if an Exception is thrown, you have to deal with an array
    JSONArray array = newObject.getJSONArray("value");
    // here, you will have an Array
}

推荐阅读