Question

I am doing JSON parsing in Android by the following steps:

  1. Get an XML response from a web-service using HttpPost object.
  2. Convert this XML to JSON string then JSON object.

Now the problem is that sometimes the XML response has null string or Null tag.

For Example:

<data>
    <name>Martin Clark</name>
    <city>London</city>
    <country>XYZ</country> or <country />     <!-- Sometimes it will blank string like this if country is not available -->
    <age>27</age>
</data>

Parsing style:

jsonObject.getString("country"); // It is working perfect when xml is this : <country>XYZ<country/>

jsonObject.getString("country"); // It is giving Exception key is not found when xml is this : <country />

i don't understand why the parser is not giving me BLANK string for blank XML object.

By deep level debugging i have found that XML to JSON converter not produce object corresponding to blank xml object.

Please help me.

Was it helpful?

Solution 2

You can use ths logical solution for your problem.

Try this once.

public static String getStringFromJSON(JSONObject json, String key){


    String value = ""; // Blank string by default.  

    try {       

        String value = json.getString(key);


        return value;
    }
        catch(JSONException exp){

        exp.getMessage();

    }

    return value;  // this wil return BLANk string if object is not prasent.

}

You can you this method for getting String from json object,

OTHER TIPS

Use optString instead, catching the Exception is costly and unnecessary.

public String optString (String name)

Added in API level 1 Returns the value mapped by name if it exists, coercing it if necessary. Returns the empty string if no such mapping exists.

public String optString (String name, String fallback)

Added in API level 1 Returns the value mapped by name if it exists, coercing it if necessary. Returns fallback if no such mapping exists.

Documentation

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top