question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

JsonParseException when encountering an empty value for an int or long

See original GitHub issue
What steps will reproduce the problem?
1. Create a data class with an int data member and a default value of 0 (any 
value would do).  Example:
public class GsonData {
    public int intValue = 0;
}

2. Create a json document with an empty value for intValue.  Example:
{
    "intValue":""
}
3. Parse the document:
String jsonString = < the json file as a string >
GsonData testDoc = new Gson().fromJson(jsonString, GsonData.class);

What is the expected output? 
I would expect that the document would parse correctly and result in intValue 
having the default value of 0.

What do you see instead?
It throws a parse exception because the empty value could not be converted to 
an int.

com.google.gson.JsonParseException: The JsonDeserializer IntegerTypeAdapter 
failed to deserialized json object "" given the type int

What version of the product are you using? 
gson-1.5.jar

On what operating system?
Windows 2008 R2

Please provide any additional information below.

Original issue reported on code.google.com by bryan.am...@gmail.com on 17 Sep 2012 at 4:00

Issue Analytics

  • State:closed
  • Created 9 years ago
  • Reactions:2
  • Comments:5

github_iconTop GitHub Comments

3reactions
schristmanncommented, Nov 12, 2018

I know this bug is closed but it’s one of the top google results when searching for this issue so I wanted to provide a broader solution to what was posted above, since it only attempts to handle empty strings

This code below will continue to correctly parse json tokens that look like ints, doubles, and strings ints and string doubles, while defaulting to 0 (or null for Integer types) on nulls, empty strings, invalid strings, and boolean values

public static final TypeAdapter<Number> UNRELIABLE_INTEGER = new TypeAdapter<Number>() {
    @Override
    public Number read(JsonReader in) throws IOException {
        JsonToken jsonToken = in.peek();
        switch (jsonToken) {
            case NUMBER:
            case STRING:
                String s = in.nextString();
                try {
                    return Integer.parseInt(s);
                } catch (NumberFormatException ignored) {
                }
                try {
                    return (int)Double.parseDouble(s);
                } catch (NumberFormatException ignored) {
                }
                return null;
            case NULL:
                in.nextNull();
                return null;
            case BOOLEAN:
                in.nextBoolean();
                return null;
            default:
                throw new JsonSyntaxException("Expecting number, got: " + jsonToken);
        }
    }
    @Override
    public void write(JsonWriter out, Number value) throws IOException {
        out.value(value);
    }
};
public static final TypeAdapterFactory UNRELIABLE_INTEGER_FACTORY = TypeAdapters.newFactory(int.class, Integer.class, UNRELIABLE_INTEGER);

Gson gson = new GsonBuilder()
    .registerTypeAdapterFactory(UNRELIABLE_INTEGER_FACTORY)
    .create();
3reactions
GokhanArikcommented, Nov 2, 2016

@GoogleCodeExporter Why won’t this issue be fixed? Isn’t this considered as a bug?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Gson.fromJson(json, Custom.class) empty string
This was suggested in JsonParseException when encountering an empty value for an int or long #472 issue but Gson team closed it because...
Read more >
SyntaxError: JSON.parse: bad parsing - JavaScript | MDN
JSON.parse() parses a string as JSON. This string has to be valid JSON and will throw this error if incorrect syntax was encountered....
Read more >
JsonParser (Jackson-core 2.7.0 API) - FasterXML
Helper method for constructing JsonParseException s based on current ... VALUE_NUMBER_INT and it can be expressed as a value of Java int primitive...
Read more >
What does an empty int means? - Arduino Forum
An integer variable will always have a value, it can't have no value. As mentioned, if it is a global variable, it will...
Read more >
Unrecognized field, not marked as ignorable - JSON Parsing ...
1) Configure Jackson's ObjectMapper to not fail when encounter unknown ... private int id; private String name; private String city; private long phone;...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found