Tsunaze
Tsunaze

Reputation: 3254

Gson deserialize with null int can't seems to work

When i download data on the web, sometimes it works and sometime it doesn't. And my problem is in one int : runtime: ""

runtime is an int and when i use gson on it can cause this problem :

01-07 21:22:57.602: E/AndroidRuntime(2726): Caused by: java.lang.NumberFormatException: Invalid int: ""

and i tried to some if statement but it doesn't work.

public int getRuntime() {
    if(Integer.valueOf(runtime)==null){
        return 0;
    }else{
        return runtime;
    }
}

or even

public int getRuntime() {
    if(Integer.valueOf(runtime).equals(null)){
        return 0;
    }else{
        return runtime;
    }
}

but nothing works.

Upvotes: 1

Views: 3916

Answers (4)

OscarSanhueza
OscarSanhueza

Reputation: 317

Handle the runtime as a string, declare it as a string in the class where you are deserializing.

Then using the gson like this will handle the nulls correctly

Gson gson = new GsonBuilder().serializeNulls().create();

This works also when serializing, normally if values are null it will just not put anything in the json to serialize.

Upvotes: 3

Brian Roach
Brian Roach

Reputation: 76908

It looks like you don't understand what exceptions are, or how to handle them:

http://docs.oracle.com/javase/tutorial/essential/exceptions

public int getRuntime() {

    int i = 0;

    try {
        i = Integer.valueOf(runtime);
    } catch (NumberFormatException e) {
        System.out.println("runtime wasn't an int, returning 0");
    }

    return i;

}

Hint: whatever runtime is, it's not anything that can be converted to an int. From what you posted, it looks like an empty String

Upvotes: 2

Thomas
Thomas

Reputation: 88707

You either need to check runtime first, e.g. if( runtime.isEmpty() ) or yet better - using apache commons lang - if( StringUtils.isBlank( runtime )) or catch the NumberFormatException that is thrown.

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691765

Integer.valueOf() expects a String representing an integer. Calling it with an empty string will lead to an exception. You need to test the String before parsing it as an integer:

int runtime;
if ("".equals(string)) {
    runtime = 0;
}
else {
    runtime = Integer.parseInt(string);
}

or, if you always want that runtime is 0 if the string is not a valid integer, then catch the exception:

try {
    runtime = Integer.parseInt(string);
}
catch (NumberFormatException e) {
    runtime = 0;
}

Now, it it's gson that parses the string for you, and this string is not always an integer, then the runtime field should not be an int, but a String. And you should parse it yourself, as shown above.

Given your question, before trying to do anything with gson and android, you should learn the basics of the Java language. You don't seem to understand the type system in Java and what exceptions are. Read http://docs.oracle.com/javase/tutorial/java/nutsandbolts/

Upvotes: 5

Related Questions