简体   繁体   中英

GSON treats integer as double

I need to read integer and double as is in String property but GSON treats every int as double (yep, i understand that it is JSON standard).

So for example I have class:

public class MyObject {
    String value;
}

In some case i've got this JSON - {"value": 1} and sometimes - {"value": 2.4} .

And i have to display this values as they are, but first value will be read as 1.0 .

I've tried to use JsonDeserializer and TypeAdapter , both have method like getAsString and both of them firstly convert value to double and then return it.

How method looks in JsonPrimitive :

@Override
public String getAsString() {
    if (isNumber()) {
        return getAsNumber().toString();
    } else if (isBoolean()) {
        return getAsBooleanWrapper().toString();
    } else {
        return (String) value;
    }
}

You can see isNumber check here.

So is it possilbe to solve this problem somehow?

public class youClass(){
  private int i;
}

and then :

Gson gson = new Gson();
yourClass = gson.fromJson(jsonText , yourClass);
yourClass.getI();

hope to be usefull

What you could do is you can get the value as String from your JSON

And create check to know the value is double or just an integer , using below a tricky way.

Try below code:

   String stringArr[] = {"1", "1.0",  "1.2", "3.5", "2.5"};
        for(int i=0;i<stringArr.length;i++){
              if(stringArr[i].equals(String.valueOf(Double.parseDouble(stringArr[i])))){
                    System.out.println("It's a double value : "+stringArr[i]);
              }else{
                    System.out.println("It's a inte value : "+stringArr[i]);
              }
        }

Output:

It's a inte value : 1

It's a double value : 1.0

It's a double value : 1.2

It's a double value : 3.5

It's a double value : 2.5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM