如何防止Gson将长数字(json字符串)转换为科学记数法格式? [英] How to prevent Gson from converting a long number (a json string ) to scientific notation format?
问题描述
我需要将json字符串转换为java对象并将其显示为long。 json字符串是一个固定的长数组:
{numbers
[268627104,485677888,506884800]}
转换的代码在所有情况下都能正常工作,除了以0结尾的数字。它将这些转换为科学注释编号格式:
public static Object fromJson(HttpResponse response,Class<?> classOf)
throws IOException {
InputStream instream = response.getResponseInputStream();
Object obj = null;
尝试{
读取器读取器=新的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;
}
实际结果:
Java对象:268627104,485677888,5.068848 E + 8
注意最后一个数字转换为科学记数法格式。任何人都可以建议可以做些什么来解决它或防止它或撤消它?我使用的是Gson v1.7.1如果序列化为字符串是您的一个选项,您可以配置GSON来完成所以:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setLongSerializationPolicy(LongSerializationPolicy.STRING);
Gson gson = gsonBuilder.create();
这会产生类似于:
{numbers:[268627104,485677888,506884800]}
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
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" ] }
这篇关于如何防止Gson将长数字(json字符串)转换为科学记数法格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!