How to prevent Gson from converting a long number (a json string ) to scientific notation format?

前端 未结 7 2181
予麋鹿
予麋鹿 2020-11-29 06:14

I need to convert json string to java object and display it as a long. The json string is a fixed array of long numbers:

{numbers
[ 268627104, 485677888, 506         


        
7条回答
  •  难免孤独
    2020-11-29 06:28

    Another work around is to use the JsonParser class instead. This will return the Gson object representations (JsonElement) rather than a user defined class, but avoids the problem of conversion to scientific notation.

    import java.lang.reflect.Type;
    import java.util.Map;
    
    import com.google.gson.Gson;
    import com.google.gson.JsonElement;
    import com.google.gson.JsonParser;
    import com.google.gson.reflect.TypeToken;
    
    public class GsonTest
    {
        public static void main(String[] args)
        {
            String json = "{numbers:[268627104,485677888,506884800]}";
    
            Gson gson = new Gson();
            Type type = new TypeToken>(){}.getType();
            Map jsonMap = gson.fromJson(json, type);
            System.out.println("Gson output:");
            System.out.println(jsonMap);
    
            JsonParser jsonParser = new JsonParser();
            JsonElement jsonElement = jsonParser.parse(json);
            System.out.println("JsonParser output:");
            System.out.println(jsonElement);
        }
    }
    

    Code Output:

    Gson output:  
    {numbers=[2.68627104E8, 4.85677888E8, 5.068848E8]}  
    JsonParser output:  
    {"numbers":[268627104,485677888,506884800]}
    

提交回复
热议问题