Search code examples
androidjavabeans

How to design javaBean in Android


I get json like :

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

I try to parser json , because I need to put key and value into 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;
    }
}

Does any one can help me ?


Solution

  • The best way is to fix your JSON issue, because it is not correct to have the same key for different value types.

    If you can't, I think you do like this :

    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
    }