gson ajax 数字精度丢失
ajax传输的json,gson会发生丢失,long > 15的时候会丢失0
解决方案:直接把属性为long的属性自动加上双引号成为js的字符串,这样就不会发生丢失了,ajax自动识别为字符串。
用法:
ajaxResult("",0,new Object()); //随便一个对象就可以,List 之类的
/**
* 以Ajax方式输出常规操作结果
*
* @param status
* 返回状态,200表示成功, 500表示错误
* @param message
* 操作结果描述
* @param tag
* 附加数据
* @return
*/
protected ActionResult ajaxResult(int status, final String message, Object tag) {
JsonObject json = new JsonObject();
json.addProperty("status", status);
json.addProperty("message", message);
String strJson = json.toString();
if (tag != null) {
StringBuffer sb = new StringBuffer();
sb.append(strJson.substring(0, strJson.length() - 1));
sb.append(",\"tag\":");
sb.append(GsonUtils.toJsonWithGson(tag));
sb.append("}");
strJson = sb.toString();
}
return writeJson(strJson);
}
/**
* 向客户端输出文本信息
*
* @param message
* @return
*/
protected ActionResult write(final String message) {
return new ActionResult() {
@Override
public void render(BeatContext arg0) throws Exception {
beat.getResponse().setCharacterEncoding("UTF-8");
beat.getResponse().setContentType("text/json;charset=UTF-8");
PrintWriter out = beat.getResponse().getWriter();
out.print(message);
out.close();
}
};
}
/**
* 向客户端输出文本信息
*
* @param message
* @return
*/
protected ActionResult writeText(final String message) {
return new ActionResult() {
@Override
public void render(BeatContext arg0) throws Exception {
beat.getResponse().setCharacterEncoding("UTF-8");
beat.getResponse().setContentType("application/text");
PrintWriter out = beat.getResponse().getWriter();
out.print(message);
out.close();
}
};
}
GsonUtils.java
package com.xxx.xxx.common.util.gson;
import com.google.gson.*;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class GsonUtils {
//private static Log logger = LogFactory.getLog(GsonUtils.class);
public static String toJsonWithGson(Object obj) {
Gson gson = createGson(); //new Gson();
return gson.toJson(obj);
}
public static String toJsonWithGson(Object obj, Type type) {
Gson gson = createGson(); //new Gson();
return gson.toJson(obj, type);
}
@SuppressWarnings("unchecked")
public static String toJsonWithGson(List list) {
Gson gson = createGson(); //new Gson();
return gson.toJson(list);
}
@SuppressWarnings("unchecked")
public static String toJsonWithGson(List list, Type type) {
Gson gson = createGson(); //new Gson();
return gson.toJson(list, type);
}
public static String toJsonWithGsonBuilder(Object obj) {
Gson gson = new GsonBuilder().setExclusionStrategies(new MyExclusionStrategy()).serializeNulls().create();
return gson.toJson(obj);
}
public static String toJsonWithGsonBuilder(Object obj, Type type) {
Gson gson = new GsonBuilder().setExclusionStrategies(new MyExclusionStrategy()).serializeNulls().create();
return gson.toJson(obj, type);
}
@SuppressWarnings("unchecked")
public static String toJsonWithGsonBuilder(List list) {
Gson gson = new GsonBuilder().setExclusionStrategies(new MyExclusionStrategy()).serializeNulls().create();
return gson.toJson(list);
}
@SuppressWarnings("unchecked")
public static String toJsonWithGsonBuilder(List list, Type type) {
Gson gson = new GsonBuilder().setExclusionStrategies(new MyExclusionStrategy()).serializeNulls().create();
return gson.toJson(list, type);
}
public static <T> Object fromJson(String json, Class<T> clazz) {
Object obj = null;
try {
Gson gson = new Gson();
obj = gson.fromJson(json, clazz);
} catch (Exception e) {
//logger.error("fromJson方法转换json串到实体类出错", e);
}
return obj;
}
/**
* 如果 Long 的数字超过15位,转换为String,在json中数字两边有引号
* @return
*/
private static Gson createGson(){
GsonBuilder gsonBuilder = new GsonBuilder();
LongSerializer serializer = new LongSerializer();
gsonBuilder.registerTypeAdapter(Long.class, serializer);
gsonBuilder.registerTypeAdapter(long.class, serializer);
Gson gson = gsonBuilder.create();
return gson;
}
public static void main(String... args) throws Exception{
// long a = 12345678901234578L;
//
// GsonBuilder builder = new GsonBuilder();
// builder.registerTypeAdapter(Long.class, new LongSerializer());
// Gson gson2 = builder.create();
// System.out.println(gson2.toJson(a));
//
// Gson gson = new GsonBuilder().setExclusionStrategies(new MyExclusionStrategy()).serializeNulls().create();
// String str = gson.toJson(a);
// System.out.println(str);
TestVO vo = new TestVO();
vo.setId(618708732263538688L);
vo.setId2(918708732263538688L);
System.out.println(toJsonWithGson(vo));
}
static class LongSerializer implements JsonSerializer<Long> {
public JsonElement serialize(Long src, Type typeOfSrc, JsonSerializationContext context) {
if(src!=null){
String strSrc = src.toString();
if(strSrc.length()>15){
return new JsonPrimitive(strSrc);
}
}
return new JsonPrimitive(src);
}
}
static class TestVO {
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
private long id;
public Long getId2() {
return id2;
}
public void setId2(Long id2) {
this.id2 = id2;
}
private Long id2;
}
}
MyExclusionStrategy.java
package com.xxx.xxx.common.util.gson;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
public class MyExclusionStrategy implements ExclusionStrategy {
private final Class<?> typeToSkip;
public MyExclusionStrategy(){
this.typeToSkip=null;
}
public MyExclusionStrategy(Class<?> typeToSkip) {
this.typeToSkip = typeToSkip;
}
public boolean shouldSkipClass(Class<?> clazz) {
return (clazz == typeToSkip);
}
public boolean shouldSkipField(FieldAttributes f) {
return f.getAnnotation(NotSerialize.class) != null;
}
}
NotSerialize
package com.xxx.xxx.common.util.gson;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface NotSerialize {
}
gson ajax 数字精度丢失的更多相关文章
- JavaScript数字精度丢失问题总结
本文分为三个部分 JS 数字精度丢失的一些典型问题 JS 数字精度丢失的原因 解决方案(一个对象+一个函数) 一.JS数字精度丢失的一些典型问题 1. 两个简单的浮点数相加 0.1 + 0.2 != ...
- JavaScript数字精度丢失的一些问题
本文分为三个部分 JS 数字精度丢失的一些典型问题 JS 数字精度丢失的原因 解决方案(一个对象+一个函数) 一.JS数字精度丢失的一些典型问题 1. 两个简单的浮点数相加 1 0.1 + 0.2 ! ...
- php导出CSV时,超长数字精度丢失问题与前导0的字符串丢失0的问题解决
php生成的CSV有时候会遇到两个特殊情况: 1.输出的字段中,含有超长数字(18位的数字)比方身份证:122121197410180016,就算输出时字段加上"",还是会被识别成 ...
- js数字精度丢失
http://www.cnblogs.com/snandy/p/4943138.html
- springboot 解决 数字长度过长导致JS精度丢失问题
问题 在开发过程中,我们的主键字段使用了数字作为主键ID,发现数字精度丢失的问题. 上图红框是后端日志的输出. 在浏览器端F12 看到的结果如上图,数据居然自动变化,这个是数字在浏览器丢失了精度,导致 ...
- JavaScript数字计算精度丢失的问题和解决方案
一.JS数字精度丢失的一些典型问题 1. 两个简单的浮点数相加:0.1 + 0.2 != 0.3 // true,下图是firebug的控制台截图: 看看java的计算结果:是不是让你很不能接受 再来 ...
- js数字位数太大导致参数精度丢失问题
最近遇到个比较奇怪的问题,js函数里传参,传一个位数比较大,打印arguments可以看到传过来的参数已经改变. 然后查了一下,发现确实是js精度丢失造成的.我的解决方法是将数字型改成字符型传输,这样 ...
- [转载]JavaScript 中小数和大整数的精度丢失
标题: JavaScript 中小数和大整数的精度丢失作者: Demon链接: http://demon.tw/copy-paste/javascript-precision.html版权: 本博客的 ...
- JavaScript数字精度上代码。
/**不能超过 9007199254740992 * floatObj 包含加减乘除四个方法,能确保浮点数运算不丢失精度 * * 我们知道计算机编程语言里浮点数计算会存在精度丢失问题(或称舍入误差), ...
随机推荐
- CENTOS下搭建SVN服务器(转)
1.安装svn yum install -y subversion 2.验证安装是否成功 svnserve --version 3.创建svn版本库 mkdir svn svnadmin create ...
- Android签名详解
1.什么是签名? 如果这个问题不是放在Android开发中来问,如果是放在一个普通的版块,我想大家都知道签名的含义.可往往就是将一些生活中常用的术语放在计算机这种专业领域,大家就开始迷惑了. ...
- ZOJ 2702 Unrhymable Rhymes 贪心
贪心.能凑成一组就算一组 Unrhymable Rhymes Time Limit: 10 Seconds Memory Limit: 32768 KB Special Judge ...
- [Office Web Apps]实现在线office文档预览
摘要 在使用office web apps实现office文档在线预览的时候,需要注意的地方. web api web api作为owa在线预览服务回调的接口,这里面核心代码片段如下: using H ...
- error: internal error: unable to execute QEMU command 'migrate': this feature or command is not cur
感谢朋友支持本博客,欢迎共同探讨交流,因为能力和时间有限.错误之处在所难免,欢迎指正. 假设转载.请保留作者信息. 博客地址:http://blog.csdn.net/qq_21398167 原博文地 ...
- 使用C#的泛型队列Queue实现生产消费模式
本篇体验使用C#的泛型队列Queue<T>实现生产消费模式. 如果把生产消费想像成自动流水生产线的话,生产就是流水线的物料,消费就是某种设备对物料进行加工的行为,流水线就是队列. 现在,要 ...
- Grid布局方式
wp7中Grid布局类似HTML中的表格,但是又不太一致! 为了测试新一个3行3列的Grid 方了方便,剔除掉其它XAML代码 [c-sharp:collapse] view plaincopy ...
- C#编程(十四)----------构造函数
原文链接:http://blog.csdn.net/shanyongxu/article/details/46501683 构造函数 所谓的构造函数就是和类名重名的且没有返回值的方法. class P ...
- 一键GHOST优盘版安装XP/win7系统
系统的安装方法有各种各样,一键GHOST优盘版也是其中的一种系统安装方法,也是俗称的U盘系统安装.下面豆豆来详细介绍下使用一键GHOST优盘版系统安装方法. 一.安装: 所谓"优盘" ...
- window消息机制
剖析Windows消息处理机制 前一段,帮人写了个小控件,又温习了一遍Windows消息处理机制,现在把一些知识点总结出来,供大家参考.1.窗口 Windows程序是由一系列的窗口构成的,每个窗 ...