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.
Related
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().
I am reading text from a longblob with table-wide default charset equal to ascii and deserializing it with Gson's fromJson(). The charset as given by another field is UTF-8. I want to serialize back a modified version, but I want to test that the serialized version is equivalent to the original text in the longblob - obviously aside from the modification.
byte[] words;//from the longblob field using getBytes()
String in = new String(words, Charsets.UTF_8);
MyClass myObj = gson.fromJson(in, MyClass.class);
//modify myObj...
String out = gson.toJson(myObj);
The problem seems to be unicode characters. The length of the Strings are not equal due to the affect unicode characters have. For example out as printed will show "we’ll" whereas in will show "we\u2019ll". I know that if I copy and paste these into java code as literals they will be equal and have equal length but in memory they are not equal in the above code.
I prefer a solution that doesn't rely on changing db field type.
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.
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
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