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

前端 未结 7 2163
予麋鹿
予麋鹿 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:26

    Got the same issue, after some investigation here is what I found.

    The behavior:

    • Gson
      For a number without fractional part, Gson would convert it as Double,
    • Jackson
      For a number without fractional part, Jackson would convert it as Integer or Long, depends on how large the number is.

    Possible solutions:

    • Convert Gson's return value from Double to Long, explicitly.
    • Use Jackson instead.
      I prefer this.

    Code - test for Jackson

    ParseNumberTest.java:

    import java.util.List;
    
    import org.testng.Assert;
    import org.testng.annotations.Test;
    
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    /**
     * test - jackson parse numbers,
     * 
     * @author eric
     * @date Jan 13, 2018 12:28:36 AM
     */
    public class ParseNumberTest {
        @Test
        public void test() throws Exception {
        String jsonFn = "numbers.json";
    
        ObjectMapper mapper = new ObjectMapper();
    
        DummyData dd = mapper.readValue(this.getClass().getResourceAsStream(jsonFn), DummyData.class);
        for (Object data : dd.dataList) {
            System.out.printf("data type: %s, value: %s\n", data.getClass().getName(), data.toString());
            Assert.assertTrue(data.getClass() == Double.class || data.getClass() == Long.class || data.getClass() == Integer.class);
    
            System.out.printf("%s\n\n", "------------");
        }
        }
    
        static class DummyData {
        List dataList;
    
        public List getDataList() {
            return dataList;
        }
    
        public void setDataList(List dataList) {
            this.dataList = dataList;
        }
        }
    }
    
    
    

    numbers.json:

    {
        "dataList": [
            150000000000,
            150778742934,
            150000,
            150000.0
        ]
    }
    

    How to run:

    • The test case is based on Jackson & TestNG.
    • Put numbers.json at the same package as ParseNumberTest.java.
    • Run as testng test, then it would print type & value of the parse result.

    Output:

    data type: java.lang.Long, value: 150000000000
    ------------
    
    data type: java.lang.Long, value: 150778742934
    ------------
    
    data type: java.lang.Integer, value: 150000
    ------------
    
    data type: java.lang.Double, value: 150000.0
    ------------
    
    PASSED: test
    

    提交回复
    热议问题