public static void main(String[] args){
String str = "{\"a\":\"48.0\", \"b\":48.0, \"c\":\"this is a string\"}";
Gson gson = new Gson();
JsonObject obj = gson.fromJson(str, JsonObject.class);
for (Object key : obj.keySet()){
String keystr = key.toString();
if (obj.get(keystr).isJsonPrimitive()){
if (obj.get(keystr).getAsJsonPrimitive().isNumber()){
System.out.println(keystr+", getting as Number: "+obj.get(keystr).getAsFloat());
}else if (obj.get(keystr).getAsJsonPrimitive().isString()){
try{
System.out.println(keystr+", getting as String-Number: "+obj.get(keystr).getAsFloat());
}catch (NumberFormatException e){
System.out.println(keystr+", getting as String-String: "+obj.get(keystr).getAsString());
}
}
}
}
}
Output:
a, getting as String-Number: 48.0
b, getting as Number: 48.0
c, getting as String-String: this is a string
I have a JsonObject which is much more complicated than the above test case. The gist of it is that the data is stored as floats in a string (example a). Occasionally, there are actual strings inside the data string such as "null" or "undef". Is there a better way to test that the string is truly a string without relying on try-catch NumberFormatException or external libraries?