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 数字精度丢失的更多相关文章

  1. JavaScript数字精度丢失问题总结

    本文分为三个部分 JS 数字精度丢失的一些典型问题 JS 数字精度丢失的原因 解决方案(一个对象+一个函数) 一.JS数字精度丢失的一些典型问题 1. 两个简单的浮点数相加 0.1 + 0.2 != ...

  2. JavaScript数字精度丢失的一些问题

    本文分为三个部分 JS 数字精度丢失的一些典型问题 JS 数字精度丢失的原因 解决方案(一个对象+一个函数) 一.JS数字精度丢失的一些典型问题 1. 两个简单的浮点数相加 1 0.1 + 0.2 ! ...

  3. php导出CSV时,超长数字精度丢失问题与前导0的字符串丢失0的问题解决

    php生成的CSV有时候会遇到两个特殊情况: 1.输出的字段中,含有超长数字(18位的数字)比方身份证:122121197410180016,就算输出时字段加上"",还是会被识别成 ...

  4. js数字精度丢失

    http://www.cnblogs.com/snandy/p/4943138.html

  5. springboot 解决 数字长度过长导致JS精度丢失问题

    问题 在开发过程中,我们的主键字段使用了数字作为主键ID,发现数字精度丢失的问题. 上图红框是后端日志的输出. 在浏览器端F12 看到的结果如上图,数据居然自动变化,这个是数字在浏览器丢失了精度,导致 ...

  6. JavaScript数字计算精度丢失的问题和解决方案

    一.JS数字精度丢失的一些典型问题 1. 两个简单的浮点数相加:0.1 + 0.2 != 0.3 // true,下图是firebug的控制台截图: 看看java的计算结果:是不是让你很不能接受 再来 ...

  7. js数字位数太大导致参数精度丢失问题

    最近遇到个比较奇怪的问题,js函数里传参,传一个位数比较大,打印arguments可以看到传过来的参数已经改变. 然后查了一下,发现确实是js精度丢失造成的.我的解决方法是将数字型改成字符型传输,这样 ...

  8. [转载]JavaScript 中小数和大整数的精度丢失

    标题: JavaScript 中小数和大整数的精度丢失作者: Demon链接: http://demon.tw/copy-paste/javascript-precision.html版权: 本博客的 ...

  9. JavaScript数字精度上代码。

    /**不能超过 9007199254740992 * floatObj 包含加减乘除四个方法,能确保浮点数运算不丢失精度 * * 我们知道计算机编程语言里浮点数计算会存在精度丢失问题(或称舍入误差), ...

随机推荐

  1. How to detect the types of executable files

    How to detect the types of executable files type { IMAGE_DOS_HEADER: DOS .EXE header. } IMAGE_DOS_HE ...

  2. 得到Revit子窗体

    start /// <summary> /// 得到主窗体句柄 /// </summary> /// <returns></returns> publi ...

  3. 使用FTP发布和更新Windows Azure网站

    在Windows Azure中,FTP的用户名和密码与管理门户的用户名和密码不一样,需要另外设置. →依次点击左侧的"网站",网站名称,右侧的"设置部署凭据", ...

  4. Android 应用开发特色

    Android 系统到底提供了哪些东西,供我们可以开发出优秀的应用程序.1. 四大组件Android 系统四大组件分别是活动(Activity).服务(Service).广播接收器(Broadcast ...

  5. ios7下UISearchBar UITextField 光标不出现的问题

    app支持ios7,在UINavBar 里面加入搜索框,结果光标一直出现不了.在overstackflow网站搜索了一下,竟然有人遇到相同的问题.... 解决办法如下: searchBar.tintC ...

  6. EBS已安装模块

    /* Formatted on 2018/3/15 11:14:51 (QP5 v5.256.13226.35538) */ SELECT fa.application_short_name , fp ...

  7. Linux线程优先级

    转自:https://www.cnblogs.com/imapla/p/4234258.html Linux内核的三种调度策略: 1.SCHED_OTHER 分时调度策略 2.SCHED_FIFO   ...

  8. Unity3D——SendMessage方法的使用

    SendMessage效率不高,因为每次调用的时候都会去遍历检测自身或者子节点上要调用的方法. 一.方法 GameObject自身的Script SendMessage("函数名" ...

  9. HTML5+Java(Spring下) 拍照上传图片

    使用支持html5的浏览器,找个有摄像头,再建一个文件接收base64字串的图片然后保存就哦了 <html> <head runat="ReYo-Server"& ...

  10. 《Python开发实战》

    <Python开发实战> 基本信息 作者: (日)BePROUD股份有限公司 译者: 盛荣 丛书名: 图灵程序设计丛书 出版社:人民邮电出版社 ISBN:9787115320896 上架时 ...