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

gson, java, json

Solution

If serializing to a String is an option for you, you can configure GSON to do so with:

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setLongSerializationPolicy( LongSerializationPolicy.STRING );
Gson gson = gsonBuilder.create();

This will produce something like:

{numbers : [ "268627104", "485677888", "506884800" ] }

Problem

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, 506884800 ] } ``` The code to convert works fine in all cases except for numbers ending in 0. It converts those to a scientific notation number format: ``` public static Object fromJson(HttpResponse response, Class<?> classOf) throws IOException { InputStream instream = response.getResponseInputStream(); Object obj = null; try { Reader reader = new InputStreamReader(instream, HTTP.UTF_8); Gson gson = new Gson(); obj = gson.fromJson(reader, classOf); Logger.d(TAG, "json --> "+gson.toJson(obj)); } catch (UnsupportedEncodingException e) { Logger.e(TAG, "unsupported encoding", e); } catch (Exception e) { Logger.e(TAG, "json parsing error", e); } return obj; } ``` The actual result: Java object : 268627104, 485677888, 5.068848E+8 Notice the last number is converted to a scientific notation format. Can anyone suggest what could be done to work around it or prevent it or undo it? I'm using Gson v1.7.1

Original source