Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

json

gson

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

like image 367
lini sax Avatar asked Jul 20 '12 20:07

lini sax


People also ask

How can you prevent Gson from expressing integers as floats?

One option is to define a custom JsonDeserializer, however better would be to not use a HashMap (and definitely don't use Hashtable!) and instead give Gson more information about the type of data it's expecting. Show activity on this post. Show activity on this post. Show activity on this post.

What is difference between JSON and Gson?

GSON can use the Object definition to directly create an object of the desired type. While JSONObject needs to be parsed manually.

Does Gson ignore transient fields?

Gson serializer will ignore every field declared as transient: String jsonString = new Gson().


1 Answers

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" ] } 
like image 132
Adam Avatar answered Sep 21 '22 09:09

Adam