I’m extracting value from XML and trying to convert it to an appropriate Object… Lets say, value can be numeric/boolean/String.
as an example…
<value> 123 </value>
<value> TRUE </value>
<value> some Strings </value>
I’m reading the value from XML as String. Any idea what would be the best approach to convert the String to the appropriate java Object? (ie. BigDecimal/Boolean/String)
This is what I’m thinking as a solution:
private Object convertParameterValIntoObject(String value){
Object toreturn = null;
BigDecimal numeric = null;
Boolean boo = null;
try{
//deal with numeric val
numeric = new BigDecimal(value.trim());
return numeric;
}
catch (NumberFormatException e) {
try{
//deal with Boolean
if(value.trim().equalsIgnoreCase("true") ||
value.trim().equalsIgnoreCase("false")){
boo = new Boolean(value.trim());
return boo;
}
else throw new Exception();
}
catch (Exception e1) {
// String
return value.trim();
}
}
}
Thanks in advance,
Hasan.
You could use java.util.Scanner which has all the type detection you need. Here’s a working example. You need to make sure you probe the type from the most specific to the least specific, here I test for boolean, then number, then string.
Output