0

Like the title , my json str sometimes like this:

{
    "data": {
        "changebaby": "no change",
        "changemama": {
            "mamacontext": "mama is a good mama",
            "mamaico": "",
            "mamatitle": "mama"
        }
    }
}

sometimes it like this:

{
    "data": {
        "changebaby": "no change",
        "changemama": "no change"
    }
}

as you see,the value of the "changebaby" key and the "changemama" key sometimes is a String, sometimes is a object, how should i parse it by gson? Could anybody help me?


Don't use the android api to parse the json string, need to use the gson lib of google to parse the json string, could anybody help me?

MayGodBlessYou
  • 649
  • 6
  • 19

5 Answers5

1

Try with this :

JSONObject changemama=jsonObject.optJSONObject("changemama");
    if(changemama== null){
         String str=jsonObject.optString("changemama");
}
Janki Gadhiya
  • 4,492
  • 2
  • 29
  • 59
Jinal Patel
  • 699
  • 5
  • 15
1
if(jsonObject.optJSONObject("changemama") != null)
{
     JSONObject changemama=jsonObject.optJSONObject("changemama");
     //Its JSON object, do appropriate operation
}
else if(jsonObject.optString("changemama") != null)
{
     //Its string, do appropriate operation
}

if you have more number of possibilities like boolean or int or long, refer this

optJSONObject

Returns the value mapped by name if it exists and is a JSONObject, or null otherwise.

Or go with the way lawrance has given : Determine whether JSON is a JSONObject or JSONArray

Community
  • 1
  • 1
Ravi
  • 34,851
  • 21
  • 122
  • 183
0

Try this code.

JSONObject data;
try {
    data = jsonObj.getJSONObject("changemama");

    // do stuff

} catch (JSONException e) {
    data = jsonObj.getString("changemama");

    // do stuff
}
V-rund Puro-hit
  • 5,518
  • 9
  • 31
  • 50
0

try this :

if(obj.has("changemama")){
   if(obj.optString("changemama").length() > 0){}
   else if(obj.optJSONObject("changemama").length() > 0){}}
Chirag Arora
  • 816
  • 8
  • 20
0

To simplyfy android development, we can ask for the backend developers to change the Mobile API.The new API could returen the json string that cann't change the value.The value of all keys cann't sometimes be a string, sometimes a object.

MayGodBlessYou
  • 649
  • 6
  • 19