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 :)
Related
I have a edit text in login page, and I have a condition for edit text MaxLength="12". In my JSON response I have a string with 15 letters (or Nor's), I need to check (or compare) up to 12 letters(or Nor's) from it, If both letters are same up to 12 Letter(or Nor's), then I have to enter into my app.
{
ID No="123456789012.00"
}
Hello Suresh Use String#substring
try {
JSONObject jObj = new JSONObject("{\"id_no\":\"123456789012.00\"}");
String strJNumber = jObj.optString("id_no").substring(0,11);
String strENumber = etNumber.getText().toString();
if(strENumber.equals(strJNumber)){
// TODO: true both are same
}else {
// TODO: true both are not same
}
} catch (JSONException e) {
e.printStackTrace();
}
You can use "substring" and "equals" methods:
(I assume your strings' names are editTextString and jsonString)
First, get substring of first 12 chars from json string:
String jsonFirst12Chars = jsonString.substring(0,12);
Then use equals method to compare them:
if(editTextString.equals(jsonFirst12Chars)) {
// They are same, do something
} else {
// They are not same..
}
I am trying to make a sign in page for an android app. My team leader has decided to make this with a webservice.
Whenever a uses logs in, a request is sent, with 3 possible responses:
0: Wrong Password
20: Wrong username
otherwise: a UUID
I am trying to validate the results given back by the webservice like this:
String resultString = result.toString();
if (resultString.equals("20")) {
Toast.makeText(getBaseContext(), "Het ingevulde emailadres klopt niet!", Toast.LENGTH_LONG).show();
return;
} else if (resultString.equals("0")) {
Toast.makeText(getBaseContext(), "Het ingevulde wachtwoord klopt niet!", Toast.LENGTH_LONG).show();
return;
} else {
Toast.makeText(getBaseContext(), "Debug, klopt", Toast.LENGTH_LONG).show();
return;
}
Seems like basic code to me. However, this code always shows the bottom statement, so it lets the first 2 pass as false.
For debugging purposes, am also returning the resultString to my console. (removed that line in the sample). There I can very obviously see that the result given back is in fact 20.
How can it be that such simple code does not do what I want it to do?
Thanks.
The code seems to be ok... Maybe a white space in the result?
Try trimming the resultString.
which es 20, result or resultString?
As an advice, it is usually better do "".equals(object) because otherwise, if the object is null it will throw NullpointerExceptcion
Regards
Response is not exactly the string you are comparing which are "0" and "20". but the response is
0: Wrong Password
20: Wrong username
otherwise: a UUID
if you want to compare the string then it should be
Options : 1
String resultString = result.toString();
if (resultString.equals("20: Wrong username")) {
// code
} else if (resultString.equals("0: Wrong Password")) {
// code
} else {
// code
}
Option : 2
Instead of eqauls you should use contains
String resultString = result.toString();
if (resultString.contains("20")) {
// code
} else if (resultString.contains("0")) {
// code
} else {
// code
}
I agree with all of the above - the code does look good.
Try using String.compareTo and look at the int returned value to check for hidden differences.
Also, try printing String.toCharArray + String.length to identify extra characters.
If you are taking the complete string returned from web service without extracting the code (0 or 20) then you need to replace 'equals' with 'contains'.
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?
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
Try with this :
JSONObject changemama=jsonObject.optJSONObject("changemama");
if(changemama== null){
String str=jsonObject.optString("changemama");
}
Try this code.
JSONObject data;
try {
data = jsonObj.getJSONObject("changemama");
// do stuff
} catch (JSONException e) {
data = jsonObj.getString("changemama");
// do stuff
}
try this :
if(obj.has("changemama")){
if(obj.optString("changemama").length() > 0){}
else if(obj.optJSONObject("changemama").length() > 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.
I succeed login and post my wall.
FB.API("me/photos", Facebook.HttpMethod.POST, Callback, wwwForm);// it works well.
FB.Feed("", "link", "link_name", ~~bulabula~~ );// it works well, too!
//////////////AND PLEASE SEE NEXT CODE. THIS IS PROBLEM.///////////////////
private string FriendSelectorTitle = "Share it with your friends!";
private string FriendSelectorMessage = "invite";
private string FriendSelectorFilters = "[\"all\"]";
private string FriendSelectorData = "{data}";
private string FriendSelectorExcludeIds = "";
private string FriendSelectorMax = "5";
private void CallAppRequestAsFriendSelector()
{
// If there's a Max Recipients specified, include it
int? maxRecipients = null;
if (FriendSelectorMax != "")
{
try
{
maxRecipients = Int32.Parse(FriendSelectorMax);
}
catch (Exception e)
{
//status = e.Message;
Debug.Log(e.Message);
}
}
// include the exclude ids
string[] excludeIds = (FriendSelectorExcludeIds == "") ? null : FriendSelectorExcludeIds.Split(',');
List<object> FriendSelectorFiltersArr = null;
if (!String.IsNullOrEmpty(FriendSelectorFilters))
{
try
{
FriendSelectorFiltersArr = Facebook.MiniJSON.Json.Deserialize(FriendSelectorFilters) as List<object>;
}
catch
{
throw new Exception("JSON Parse error");
}
}
FB.AppRequest(
FriendSelectorMessage,
null,
FriendSelectorFiltersArr,
excludeIds,
maxRecipients,
FriendSelectorData,
FriendSelectorTitle,
Callback
);
}
void Callback(FBResult result)
{
Debug.Log(result.Text);
}
/////////////////////////////////////////////////
it look like works well.
first, pop up friends selector dialog,
and I clicked some friends, and click 'done' button.
it will call 'Callback' Funtion, and
debug.log(FBResult.text); show follow like this.
{"request":"8939391818800568","to":["2446462595631736"],["189238719238719238"]}
but now, I don't know how to use these values. T_T
I think FB.feed(); is well done. So,
I try to
for( int i=0; i<usernum; i++ )
{
FB.feed( "id[user_index]" , bula~bula );
}
but failed.
becuase, fbresult.text is not string!!?
I try to split this string(fbresult.text), to get "to":["userid1 number"], ["userid2 number"]
but I failed and disappointed.
please someone help me.
Anybody who has a good idea???
I really want to send my message(pic or message) to friend's facebook wall.
You canĀ“t post to the wall of a friend anymore, since a very long time. In most (all?) cases this would be considered as spam, so they remove that possibility.
You can use the Send Dialog to send something to a friend, for example.
I'm trying to get the user's cover photo and show it at the top of a layout. I'm using AsyncTask to run the API call to Facebook. The code I'm using to get the Facebook data is
JSONObject json = null;
response = Utility.facebook.request("me?fields=cover");
json = Util.parseJson(response);
The exception that stops the thread comes from a json error on the next step because the returned json is empty, even though the request clears through. I can get a proper json using just "me" or "me/albums" or anything other than "me?fields=cover". When I comment out the last line, 'try' process finishes with no exceptions/errors.
Is there something wrong with the Facebook API or am I doing something wrong?
I personally prefer using FQL when dealing with User Profile. If you would like to give FQL a try, check the following piece of code. If you would like to stick to Graph API, see this answer: https://stackoverflow.com/a/12434640/450534
try {
String query = "SELECT pic_cover FROM user where uid = " + PUT_THE_USER_ID_HERE;
Bundle param = new Bundle();
param.putString("method", "fql.query");
param.putString("query", query);
String response = Utility.mFacebook.request(param);
JSONArray JAUser = new JSONArray(response);
for (int i = 0; i < JAUser.length(); i++) {
JSONObject JOUser = JAUser.getJSONObject(i);
// COVER PHOTO
if (JOUser.has("pic_cover")) {
String getCover = JOUser.getString("pic_cover");
if (getCover.equals("null")) {
String finalCover = null;
} else {
JSONObject JOCoverSource = JOUser.optJSONObject("pic_cover");
if (JOCoverSource.has("source")) {
String finalCover = JOCoverSource.getString("source");
} else {
String finalCover = null;
}
}
} else {
String finalCover = null;
}
}
} catch (Exception e) {
// TODO: handle exception
}
The above code already accounts for User's who do not have a Cover Photo set in their profiles and checks for its availability. With this code, you will have the URL to the Cover Photo and can then process it as you prefer.
NOTE: If you are fetching the logged in users cover photo, this piece of code SELECT pic_cover FROM user where uid = " + PUT_THE_USER_ID_HERE; can also be written as: SELECT pic_cover FROM user where uid = me()"; For the non-logged in user's cover photo, the above can be used as is.
Couple of things as a side note.
I use Fedor's Lazy Loading technique to load images in almost exclusively.
I recommend running the code block, mine or any other solution you choose, in an AsyncTask.
The reason for not getting any result can be found in the javadoc of request(String graphPath) method:
(...) this method blocks waiting for a network response, so do not
call it in a UI thread.
In your case, you should probably do the following synchronous call:
Bundle params = new Bundle();
params.putString("fields", "cover");
String result = Utility.facebook.request("me/", params);
Siddharth Lele is very correct in his answer, but I wanted to specify the actual reason for not getting any response in this case.
Note: Fetching Cover Photo using Facebook API and endpoint https://graph.facebook.com/me?fields=cover no longer works as on 20th Dec 2014.
It was supposed to give following response:
{
"cover": {
"cover_id": "10151008748223553",
"source": "http://sphotos-a.ak.fbcdn.net/hphotos-ak-ash4/s720x720/391237_10151008748223553_422785532_n.jpg",
"offset_y": 0
},
"id": "19292868552"
}
But now it just gives User's id:
{
"id": "19292868552"
}
Verified this using Graph Tool explorer v2.2 using me?fields=cover.