The difference between getString() and optString() in Json - java

What is the difference between getString() and optString() in JSON?

As Diego mentions, it's a good idea to check the documentation (this link is now out of date - good thing we have the Wayback Machine!) before posting a question here, but now that you have:
The difference is that optString returns the empty string ("") if the key you specify doesn't exist. getString on the other hand throws a JSONException. Use getString if it's an error for the data to be missing, or optString if you're not sure if it will be there.
Edit: Full description from the documentation:
Get an optional string associated with a key. It returns an empty string if there is no such key. If the value is not a string and is not null, then it is converted to a string.

If you want to avoid NullPointerException you better make use of optString()
If you are fetching the data from JSON at any time, you might have null data for a particular Key value, at that time instead of implementing Null conditions, better make use of this optimized method optString("<keyname>")

public java.lang.String optString(int index)
Get the optional string value associated with an index. It returns an empty string if there is no value at that index. If the value is not a string and is not null, then it is coverted to a string.
Parameters:
index - The index must be between 0 and length() - 1.
Returns:
A String value.

1) getString (String name):- This method Returns the String value mapped by name if it exists, coercing it if necessary, or throws JSONException if no such mapping exists.
2)optString (String name):- This method Returns the String value mapped by name if it exists, coercing it if necessary, or the empty string ("") if no such mapping exists.

optString() is used to overcome NullPointerException, which we get while using getString() when the required key doesn't exists in json it basically replaces with the default value.
example let the input Json be
{
"name":"abhi",
"country":"india"
}
now in java when you execute
String city = json.getString("city");
it will throw a NullPointerException.
by using optString(String key, String default) we can overcome the above problem.
String city= json.optString("city","default");
System.out.println(city);
Output: default

Related

getValue(String.class) vs getValue().toString()

this is an example for a question asked here :
getValue(String.class) vs getValue().toString();
I had stored into my firebase table a child "Vyear" as Integer and it looked as such
and I used to retrieve it as below, and the app was always crashing ;
child4.child("Vyear").getValue(String.class);
after reading the question, and the answers , I solved my problem and now I am using;
child4.child("Vyear").getValue().toString();
Your first snippet:
child4.child("Vyear").getValue(String.class);
This retrieves the String value from Vyear. Since Vyear stores a numeric value, it means that the snippet returns null.
The second snippet:
child4.child("Vyear").getValue().toString();
This returns the value from Vyear in its underlying type. So if Vyear has a value, this returns a number (a long or Long). Calling toString() on that, gives you the number as a string.
Note that in case Vyear does not exist, the second snippet will thow a NullPointerException on the call to toString().

optstring not converting to string [aws json object]

I am using com.amazonaws.util.json.JSONObject
In the documentation it says
public String optString(String key)
Get an optional string associated with a key. It returns an empty string if there is no such key. If the value is not a string and is not null, then it is coverted to a string.
Parameters:
key - A key string.
Returns:
A string which is the value.
I have a json object like {"time":1505900658464} and when i use optstring i expect it to convert this long value to string ,but it actually returns " " (instead of converted long values as string).Am i missing something?
First, the optString() method is supposed to return empty string: "" if there is no available String value.
See the Documentation.
Second, the object {"time":1505900658464} has long value not string. You should use optLong instead. See the Documentation.
Also, you might need to read this discussion, and for converting time from Unix (that's the format you provided in your example) to simpleDateFormat see this.

What does is mean by null pointing to nothing and why use null at all?

There are a lot of questions about null and in java.
What I am failing to grasp is what people mean by null is pointing to nothing or why to use null at all.
I can't understand the difference between
String thing = null;
and
String thing = "";
This question has detailed answers What is null in Java?, but I just can't wrap my head around it.
What am I missing?
languages I've studied (no expert)
Python, vb (vb.net), web programming (html, css, php, bit of js), sql
I should add, it is this answer https://stackoverflow.com/a/19697058/2776866 which prompted me to write this.
String str = null;
means a String reference, named str, not pointing to anything
String str = "";
means a String reference, named str, pointing to an actual String instance. And for that String instance, it is a zero-length String, but it is still an actual object.
Just a little update with some diagram which hopefully can help you visualize that:
assume I have
String nullStr = null;
String emptyStr = "";
String myStr = "ab";
What it conceptually is something look like:
// String nullStr = null;
nullStr ----------> X pointing to nothing
// String emptyStr = "";
+------------------+
emptyStr ---------> | String |
+------------------+
| length = 0 |
| content = [] |
+------------------+
// String myStr = "ab";
+------------------+
myStr ------------> | String |
+------------------+
| length = 2 |
| content = [ab] |
+------------------+
(of course the internal structure of the String object is not the real thing in Java, it is just for giving you an idea)
More edit for the rationale behind NULL:
In fact in some language they do not provide concept of NULL. Anyway, in Java (or similar language), Null means semantically different from "empty" object. Use String as an example, I may have a People class with a String preferedTitle attribute. A Null preferedTitle means there is NO preferred title for that people (so that we need to derive and show the title for it, maybe), while a preferedTitle being an empty string means there IS a preferred title, and that's showing nothing.
Btw, although a bit off topic: concept of Null is seen as problematic for some people (because all those extra handling it need etc). Hence some languages (e.g. Haskell) are using some other ways to handle the situation where we used to use Null.
String str is a reference to an object. That is, it's not an actual object, but a variable which can contain the address of an object. When you assign a value to str you are changing the address stored within and changing which object it addresses.
null is reference value which points to no object. It's about as close to nothing as you can get. If you assign null to a String reference (String str = null;), you cannot then invoke any method of String using that reference -- all attempts will result in NullPointerException.
"" is a character String which contains no characters -- zero length. It is still an object, though, and if you assign its address to your String reference variable (String str = "";) you can then take its length, compare it to another String, extract its hashCode, etc.
Java doesn't really expose pointers, instead it deals with references.
When you say
String thing = null;
You are saying that there is a reference (of type string) called thing, which isn't referencing anything.
When you say
String thing = ""
This is shorthand for,
String thing = new String("");
Now you have an actual object initialized and ready to be used. You told the compiler to create a string and now your "thing" references the new string.
If you want to know the length of your initialized string, you can go;
thing.length
Which is zero. The string exists, but is zero length.
Trying string.length on the null version causes a NullReferenceException, which is the compiler saying
"I tried to find out about the length of your string, but I couldn't find it!"
Practically speaking, null means "not available for calling methods". If an object is allowed to be null, you must always check it for null before calling method on it.
An attempt to call any method on a null object is unconditionally an error. In nearly all cases it's a programming error, too, because you are supposed to either
Ensure that a variable is always non-null, or
Check a variable that could legally be null before calling methods on it.
On the other hand, an empty object lets you call methods. For example, you can find the length of an empty string - it is zero. You could also iterate a string, pass it to methods that expect non-null strings, and so on.
To visualize this, consider a Boolean object instead of a String. Unlike the primitive boolean that has only two states, namely true ("yes") and false ("no"), the Boolean object has three states:
Yes
No
Don't know
This third "don't know" state corresponds to null. It's neither true nor false state. Your program can use this third state to its advantage - for example, you can use comparison to null to see if a value has been set, or set a value to null to "unset" its value.
In Java null and an empty String are two different things.
If an String is null then you can not access its methods as it will throw a NullPointerException, however if a String is "" then the String object is valid and you can access its methods.
For example
String a = null;
String b = "";
System.out.println (a.length()); // No Good
System.out.println (b.length()); // Prints 0
Let's compare this to Python. In Python, the equivalent to null is None.
>>> test = ""
>>> test1 = None
This is setting an empty string and a "null" string.
>>> test
''
>>> test1
None
In Python we can test nullity using is
>>> test is None
False
>>> test1 is None
True
We can test for empty strings using ==
>>> test == ""
True
>>> test1 == ""
False
null (like None) is the absence of a value.
Conceptually null is a special value which means that the variable points to an invalid object, so it doesn't refer to anything valid in the sense that you can't access its content (variables or methods).
You can see it as a sort of special condition which has been added to languages because it was useful to be able to have pointers that refer to nothing. But there is some discordance here, in fact some languages prevent the necessity of a null value by forcing you to have just inizialized (meaningful) values.
There is difference in your example, "" is a valid object: it's an empty string while null is not a valid object.
Although many object-oriented frameworks implement references with pointers, it is better to think of references not as "pointing to" objects, but rather as "identifying" them [personally, I like the term "object identifier" to describe references, since the term "reference" is somewhat overloaded in different contexts]. Although object identifiers are not human readable, one can imagine the system as giving each object an associated number starting at 1, and each class-type variable as either having an object number or a zero written on it. Since class-type variables and array slots default to holding zero, and there will never be a zeroth object, there's no danger that the default-valued variable of an uninitialized variable or array slot will identify a valid object.
I prefer using the concept of containers/boxes to understand this concept
Let's start with this
String thing = "";
Imagine you have a container/box where you can store any value as long as you put the value between double quote marks "", if you decide to just put the double quotation mark without a value inside the box there is absolutely nothing wrong with that and any time you open your box you still see something inside (The double quotation mark )
Now This big man over here called null
String thing = null;
In simple terms look at null as being absolutely nothing
What does all this mean?
When you open the first box you see the double quotation ""
When you open the second box you see nothing (it's just an empty box)

Assign property value with type conversion in Java

What is the best way to assign a value with type conversion to a property of an object in Java.
For eg: A Person class with age field as an integer. If the following statement has to assign integer 21 to age field, then what should be the implementation of set method? [Note: 21 is passed as string]
ObjectUtils.set(person, "age", "21");
One way is to get the type of the field and type cast explicitly. Is there any better approach or library utility available to achieve this?
Take a look at BeanUtils.setProperty():
Set the specified property value, performing type conversions as required to conform to the type of the destination property.
You can achieve this by using reflexion:
using this you can get the attribute type dynamically, something like this:
Person p = ...; // The object you want to inspect
Class<?> c = p.getClass();
Field f = c.getDeclaredField("age");
f.setAccessible(true);
String typeOfAge = (String) f.getType(p);
After you have the attribute type its easy to cast the value.
use Integer.parseInt(String) in your set method. Make sure you catch the exception for an invalid number. Here is hte javadoc for parseInt
parseInt
public static int parseInt(String s) throws NumberFormatException Parses the string
argument as a signed decimal integer. The characters in the string
must all be decimal digits, except that the first character may be an
ASCII minus sign '-' ('\u002D') to indicate a negative value. The
resulting integer value is returned, exactly as if the argument and
the radix 10 were given as arguments to the parseInt(java.lang.String,
int) method. Parameters: s - a String containing the int
representation to be parsed Returns: the integer value represented by
the argument in decimal. Throws: NumberFormatException - if the string
does not contain a parsable integer.

String equality comparison failure in Java

I'm taking a one string value from an object in a object list.
transitionName = transitionList.get(m).getTransitionName().toString();
And another string value from an object retrieved by a EJB query.
changeItem = changeItemFacade.getChangeItem(changeGroupList.get(1));
char tempNewString[] = changeItem.getNewstring();
newString=new String(tempNewString);
Now this Char[] to String comparison is because the Oracle Table which contains the changeItem have defined the coloumn NewString as a CLOB.
And the ejb entity defines type of the variable 'NewString' as a Char[] array .
So i have to convert it to a string before doing the comparison.
The problem is that this if statement always returns false and doesn't get executed.
if(transitionName.equalsIgnoreCase(newString)){}
When i try to Log the values (Logger.Debug) , It perfectly show the two (equal) string values in the Server Instance log.
Is there something wrong with the way i convert the char[] array?
I tried changing the type of the entity class variable to String(and of course also the getter and setter methods) but doesn't work either.
Try trim() on strings before comparing. Also, look for character encoding differences. – Singularity

Categories