Ignore case for JSON-Keys in Android
i'm using in my android开发者_运维问答 app native JSON-Library within Android OS. It works fine, but one thing makes me crazy.
If server interface changes and gives almost the same answer but the key notation will be a bit different (e.g. examplekeyofmyapp and exampleKeyOfMyApp) i have a problem.
Is there the way to ignore the case of the keys?
Or maybe anybody of you uses a workaround for these cases?
Thank you
if you had implemented your code like this
jsonobject.get(examplekeyofmyapp)
;
then modify your code. simply change the json String to lower case.
jsonString.toLowerCase()
. thats it, all the upper case will get converted to lower case.
I faced the same problem and the best solution I found is to check if your key has an available value.
You still have to check all the possible cases you think you could have.
String TAG_URL_LOWER_CASE = "url";
String TAG_URL_UPPER_CASE = "URL";
String urlValue = "";
if (!obj.isNull(TAG_URL_LOWER_CASE)) {
urlValue = obj.getString(TAG_URL_LOWER_CASE);
} else if (!obj.isNull(TAG_URL_UPPER_CASE)) {
urlValue = obj.getString(TAG_URL_UPPER_CASE);
}
You will also avoid JsonException if your key has no value associated to you key. Hope it helps
I know this is a few years old, but I thought my solution might help others:
String keyName = null;
for(Iterator<String> iter = jsonData.keys(); iter.hasNext();) {
String key = iter.next();
if (key.equalsIgnoreCase(jsonVar)) {
keyName = key;
break;
}
}
jsonData.get(keyName);
Obviously you can change the "get()" to other types of get methods
I have core methods that I use for each of the types that handles the error for you, e.g.
public static String getJSONString(JSONObject jsonData, String jsonVar) {
// start with a blank name
String keyName = null;
// loop through they keys to find the correct spelling
for(Iterator<String> iter = jsonData.keys(); iter.hasNext();) {
String key = iter.next();
if (key.equalsIgnoreCase(jsonVar)) {
keyName = key;
break;
}
}
// if the key isn't found, return a null
if (keyName == null) {
return keyName;
}
// need a try/catch around JSON stuff as the variable could be the wrong type or not exist
try {
return jsonData.getString(keyName);
}
catch (Exception e) {
// log the variable & the error
Log.w("getJSONString", "failed to getJSONstring "+jsonVar+" - "+e.toString());
// return an empty string because the "get" failed
return "";
}
}
Once you have all of the types made, it makes it easier to handle blank or missing values
I hope this helps somebody :)
精彩评论