GSON Exceptions - Print Field Names That Give Nan Serialization Errors

I am using Gson, I encountered the problem of serializing an object:

java.lang.IllegalArgumentException: NaN is not a valid double value as per JSON specification. To override this behavior, use GsonBuilder.serializeSpecialFloatingPointValues() method. at com.google.gson.Gson.checkValidFloatingPoint(Gson.java:296) ... 

Is there a way for Gson to print the class name / field name it encounters? I can use the serializeSpecialFloatingPointValues() method as suggested, but ideally I would like to understand where my objects have NaN.

-------- Update ----------------

After carefully overcoming this, I believe that the cause is an uninitialized double. My setup looks like this:

 public class Foo { private double price; } String jsonFromNet = ...; Foo foo = Gson.fromJson(jsonFromNet); Gson.toJson(foo, Foo.class); <-- throws the exception 

Returning json from my api does not include the β€œprice” attribute, so I think the member variable β€œd” remains uninitialized. When I proceed to serialize it, gson throws an error.

If I give the "price" an explicit value before serialization or, as it turned out, in the api json answer, everything works fine.

Also, if I change the "price" from double to float, this does not look like an uninitialized state.

Now I will look at GsonBuilder.serializeSpecialFloatingPointValues ​​(), I'm just wondering how dual serializes in this state. I would be fine with the default value of zero or something.

thanks

+6
source share
1 answer

Strictly speaking, the answer is no. I checked the source code and as far as I know, I don't see the point when you can tweak the behavior to get what you need using Gson.

But when we think about this answer, 4 ideas come to my mind to get the necessary information. The ultimate goal is to determine the field at all costs, right?

  • Download the Gson code, set a breakpoint before the exception is thrown in the checkValidFloatingPoint method and check the boundField.name value in com.google.gson.internal.bind.Adapter<T>.writ e. This field is for violation.
  • Download the Gson code and configure the previous point method to print the violation field when an IllegalArgumentException is caught. (suggest a patch;))
  • Using serializeSpecialFloatingPointValues() , serialize the JSON string, then, using regular expression lookups, find each Nan string in the string. Nearby is the name of the field or the name of the field of the array you are looking for.
  • Create your own class scanner, which through reflection checks each double field to see if it is null. Of course, in this case, Gson does not need to. In any case, this would be an interesting exercise.
0
source

Source: https://habr.com/ru/post/954274/


All Articles