{"success":"1","info":{"created":"2012-8-30 16:47:59","country":"Ghana","user_id":"2","onlinestatus":"1","last_login_datetime":"2013-3-2 22:13:10","nickname":"badu","discover":"0"},"interests":[" cook","eat"]}Interests is an array of values. The doc specifies updating interests at such
interests - comma separated list of interestsObviously, a suitable method for converting between arrays and a comma separated string value(s) is required. Unfortunately for Java and by extension J2ME, they never bothered to think that people might implementations similar to split and join in Python. So here goes..
1. Split first. Very simple method for splitting a string into an array along defined separators
public String[] split(String original, String separator)2. Now the slightly harder part. Convert the returned array in the json response to a string. First problem here is that getting the array involves returning it as a JSONArray which apparently is not castable to a normal String Array. So this is how you do it...
{
Vector nodes=new Vector();
//Parse nodes into Vector
int index=original.indexOf(separator);
while(index>=0){
nodes.addElement(original.substring(0, index));
original=original.substring(index+separator.length());
index=original.indexOf(separator);
}
//Get the last node
nodes.addElement(original);
//Create split array
String[] result=new String[nodes.size()];
if(nodes.size()>0){
for(int loop=0; loop<nodes.size(); loop++)
{
result[loop]=(String)nodes.elementAt(loop);
}
}
return result;
}//--End of split()
//Convert JSONArray to String ArrayThis is followed by the join method which I implemented as such:
JSONArray key_array = json.getJSONArray("interests");
String[] key_attributes = new String[key_array.length()];
for(int i=0; i<key_array.length(); i++){
key_attributes[i] = key_array.getString(i);
}
public String join(String[] array, char separator){Now calling the method join, you MUST remember to provide the separator as a character. In java, it's not easy to type out a character variable in code and instead, one has to go around like this:
//Catch empty array
if (array == null) return null;
if(array.length == 0) return null;
String joined_string = "";
for(int i=0; i<array.length;){
joined_string += array[i] + separator;
i++; //Don't forget to increment
}
//Truncate trailing seprator
return joined_string.substring(0, joined_string.length()-1);
}//--End of join()
String separator = ",";There you go folks, all done with Java's usual unfriendly long way of getting simple things done.!
interests = join(key_attributes, separator.charAt(0));
No comments:
Post a Comment