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
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.
GSON can use the Object definition to directly create an object of the desired type. While JSONObject needs to be parsed manually.
Gson serializer will ignore every field declared as transient: String jsonString = new Gson().
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" ] }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With