1

I'm using Gson to (de)serialize between Json string and Java Object, it's convenient but, when the string contains some invalid value, gson only returns exception and states the type of exception.

For example, I have some class like :

public class Employee {
    public String name;
    public Integer age;
}

If I try to deserialize like this :

try {
    String data = "{\"name\":\"Alan\",\"age\":\"twenty-eight\"}";
    Employee employee = gson.fromJson(data, Employee.class);
} catch (Exception e) {
    logger.warn(e);
}

It outputs

java.lang.NumberFormatException: For input string: "a"

Is there any method to know the invalid field("age" in this case) as well? I've referenced question, but it seems not suitable in this case.

Alanight
  • 353
  • 2
  • 8
  • 23

2 Answers2

0

I'm afraid, you cannot do that as of Gson 2.8.4. If you check the stacktrace, you can see:

Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.NumberFormatException: For input string: "twenty-eight"
    at com.google.gson.internal.bind.TypeAdapters$7.read(TypeAdapters.java:228)
    at com.google.gson.internal.bind.TypeAdapters$7.read(TypeAdapters.java:218)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:131)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:222)
    at com.google.gson.Gson.fromJson(Gson.java:922)
    at com.google.gson.Gson.fromJson(Gson.java:887)
    at com.google.gson.Gson.fromJson(Gson.java:836)
    at com.google.gson.Gson.fromJson(Gson.java:808)

Neither ReflectiveTypeAdapterFactory.java:131 nor ReflectiveTypeAdapterFactory.java:222 propagate the fields they work on to thrown exceptions. It looks like an issue and seems worthy to file a bug report to Gson.

Lyubomyr Shaydariv
  • 20,327
  • 12
  • 64
  • 105
0

I'm trying to work around a similar problem (in my case I actually want to continue processing the json, but it seems you cannot do it easily).

In any case you can get the path of the field that cause the exception with reader.getPath().

Also get the value based on the token: JsonToken token = reader.peek(); And a switch based on the token value so if JsonToken.STRING, get the value with reader.nextString(), and so forth.

mon
  • 1
  • 2