Get property value and check for existence and null - android

I am writing a custom deserializer for a json object and I have a property in the json that may not exist and if it exists its value may be null.
JsonObject obj = ....;
String value = "";
// first check if exists
if (obj.has("someProperty")) {
// get the proprty
JsonElement element = obj.get("someProperty");
// better check if its null
if (!element.isJsonNull()) {
// ah yes finally have the value
value = element.getAsString();
}
}
Yup works great, but extremely verbose. Combing the GSON api to find a better way with no luck. Is there an easier way?

Maybe this one would be a little bit better:
JsonElement element = obj.get("someProperty");
if (element != null && !element.isJsonNull()) {
value = element.getAsString();
}

You should use org.json.JSONObject; and do the following.
JSONObject obj1 = new JSONObject();
String value = "";
// will set value to your element if it exists otherwise will return empty string
value = obj1.optString("someProperty");

Related

Android, Iterate over JSON-fied dictionary

I have the following string, which was created using javascript JSON. (It's passed from a Webview to the native code using JavascriptInterface.)
{"var1":1,"var2":8}
How do I convert that into an object and then iterate over the key/value pairs? The names of the keys are NOT known in advance.
I have seen this JSON Array iteration in Android/Java and this Converting json string to java object? and this how to convert JSON string to object in JAVA android.
None of those seem to fit with my example, which is a dictionary with unknown key names. At least, it's certainly not clear to me which of the 15+ answers is relevant for my case.
The org.json library comes "for free" with Android, so I'd go with that. Usage when you don't know the keys ahead of time could be something like this:
try {
JSONObject jsonObject = new JSONObject(/* your json String here */);
Iterator<String> keys = jsonObject.keys();
while (keys.hasNext()) {
String key = keys.next();
String value = jsonObject.getString(key);
// do whatever you want with key/value
}
}
catch (JSONException e) {
// thrown when:
// - the json string is malformed (can't be parsed)
// - there's no value for a requested key
// - the value for the requested key can't be coerced to String
}
You can use it by converting the getting the json length like this:-
JSONObject obj = new JSONObject(response);
for (int i = 0; i < obj.length(); i++) {
//getting the json object of the particular index inside the array
JSONObject heroObject = obj.getJSONObject(i);
String aka=heroObject.getString("your key here");
}

Compare Two JSONArray In Android

I want to compare two JSONArray with the same value with different order how compare it. This code work fine if value place in the same index.
String a = "[\"ABC-110101-056079-0001\",\"CBA-111101-056079-0001\",\"BCD-110101-056079-0011\"]";
String b = "[\"ABC-111101-056079-0001\",\"CBA-110101-056079-0001\",\"BCD-110101-056079-0011\"]";
JSONArray jsonArraya = null;
JSONArray jsonArrayb = null;
try {
jsonArraya = new JSONArray(a);
jsonArrayb = new JSONArray(b);
} catch (JSONException e) {
e.printStackTrace();
}
if (jsonArraya.equals(jsonArrayb)) {
Log.i("TAG",str2 is equal to str1 = " + "true");
}
You could add the elements of each array to a SortedSet instance and compare those:
SortedSet<Object> seta = new TreeSet<>();
jsonArraya.forEach(seta::add);
SortedSet<Object> setb = new TreeSet<>();
jsonArrayb.forEach(setb::add);
Log.i("TAG", "str2 is equal to str1 = " + seta.equals(setb));
The best solution in this situation is to parse values of those arrays first using Gson into POJO files, After that create .equals() method, which will add all strings from array into Set<>.
Then iterate over one set and remove all current item from another set and remove the same elements. Both objects are the same if at the end there will be no elements in the second set.

Handling null in JSONObject

My app uses Eventbrite API and it crashes when event logo is null.
JSONObject jsonRootObject = new JSONObject(event);
JSONArray jsonArray = jsonRootObject.optJSONArray("events");
JSONObject jsonObject = jsonArray.getJSONObject(i);
information = jsonObject.getJSONObject("logo");
text = information.getString("url");
name = "eventsImage" + i;
resId = getResources().getIdentifier(name, "id", getPackageName());
new LoadImagefromUrl().execute(new LoadImagefromUrlModel(text, resId));
I am trying to make exception for this event, but I am not very experienced with JSONObjects and I don't know how if statement should look like
I have tried the following, but it didn't work
jsonObject.getJSONObject("logo")!=null
You have to catch JSONException in
information = jsonObject.getJSONObject("logo");
like
try{
information = jsonObject.getJSONObject("logo");
}catch(JSONException je){
//json object not found
}
See this link
which says - public JSONObject getJSONObject (String name)
Returns the value mapped by name if it exists and is a JSONObject, or throws otherwise.
OR, You can use optJSONObject like this -
if(jsonObject.optJSONObject("logo")!=null)'
Because optJSONObject doesn't throws exceptions instead returns null if no key found
It crashes because you are trying to retrieve an object that does not exist. If object might be null you should be using jsonObject.optJsonObject("logo") instead.

check for empty fields android

code gets two user inputs from user and compares inputs to a database and prints out d corresponding data from the database.how do i add code to check for empty fields?
protected void onPostExecute(Void v) {
try {
boolean available=false;
JSONArray Jarray = new JSONArray(result);
for(int i=0;i<Jarray.length();i++) {
JSONObject Jasonobject = null;
//text_1 = (TextView)findViewById(R.id.txt1);
Jasonobject = Jarray.getJSONObject(i);
//get an output on the screen
//String id = Jasonobject.getString("id");
String name = Jasonobject.getString("name");
String name1 = Jasonobject.getString("name1");
String db_detail = "";
if (et.getText().toString().equalsIgnoreCase(name) && et1.getText().toString().equalsIgnoreCase(name1)||et.getText().toString().equalsIgnoreCase(name1) && et1.getText().toString().equalsIgnoreCase(name)) {
db_detail = Jasonobject.getString("detail");
text.setText(db_detail);
available = true;
break;
}
}
if(!available)
Toast.makeText(MainActivity.this, "Not available", Toast.LENGTH_LONG).show();
this.progressDialog.dismiss();
}
Use TextUtils.isEmpty(charactersequence)
if(!TextUtils.isEmpty(et.getText().toString().equalsIgnoreCase(name)))
{
}
Docs :
public static boolean isEmpty (CharSequence str)
Added in API level 1
Returns true if the string is null or 0-length.
Parameters
str the string to be examined
Returns
true if str is null or zero length
Also better to use optString
Jasonobject.optString("name");
You can use String.isEmpty() method which checks whether the length of the String is 0.
You can also try on String.matches().
Using equalsIgnoreCase("") performs an actual string comparison. This method returns true if the argument is not null and the Strings are equal, ignoring case; false otherwise.
So you may check using isEmpty() or matches("") method to check empty values and then do the comparison.
suppose your string you received is as below,
String nameString = jsonObj.getString("name");
you can check if its empty by using following check.
if(nameString.equals(""))

Parsing JsonObject's fields regardless of their name

I've been looking for this for a while now, but couldn't find it anywhere in SO or in the docs.
I am using Gson to parse a json file, and suppose the file is:
{
"animal":"cat",
"paws":"4",
"eyes":"2"
}
Now, since all the fields are strings, I want to parse it as an array of strings, I want something like:
{"cat","4","2"}
And I would like to parse the JsonObject regardless of the name of its tags, and that's where the problem lies. I can garantee the json will contain only strings, but I have no clue of what the fields are going to be named.
Anyone ever faced this problem ? Any help is much appreciated, and any research direction also.
Edit
From the anwers, I managed to do it like this:
for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
// do your stuff here
}
as explained in this answer
JSONObject has the keys() method that returns an Iterator<String>. Through the iterator you can retrieve the value associated with each key. Here the documentation
EDIT:
Since you are using GSON , you can retrieve the keys through the method entrySet()
You should use Iterator, which you can get by calling .keys() on your JSONObject. I think something like that should work (using org.json library):
String[] output = new String[jsonObject.length()];
Iterator iterator = jsonObject.keys();
int i = 0;
while (iterator.hasNext()){
output[i++] = jsonObject.optString((String) iterator.next());
}
EDIT Ok, in case of GSON it will be like this:
Set<Map.Entry<String, JsonElement>> set = jsonObject.entrySet();
String[] out = new String[set.size()];
int i = 0;
for (Map.Entry<String, JsonElement> x : set){
out[i++] = x.getValue().toString();
}
If you are using gson then simple solution is :
Type mapType = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> map = gson.fromJson(YOUR_JSON_STRING, mapType);
// get only values from map
Collection<String> values = map.values();
for (String string : values) {
// do your stuff here
}
result values collection contains
[cat, 4, 2]
JSONObject jsonObject = new JSONObject(parentJson.getJSONObject("objectname")
.toString());
Iterator<?> iter = jsonObject.keys();
while (iter.hasNext()) {
String key =(String) iter.next();
String value = jsonObject.getString(key);
}

Categories

Resources