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. 设计模式之七:模板方法模式(Template Method)

    模板方法模式: 定义了一个算法的基本操作骨架,并将算法的一些步骤延迟到子类中来实现. 模板方法模式让子类在不更改算法结构的前提下能够又一次定义算法的一些步骤. Define the skeleton ...

  2. 各种版本的ST-LINK仿真器

    1.ST官方正式出版了两种仿真器:ST-LINK.ST-LINK/V2,其他型号(ST-LINK II,ST-LINK III,…)要么是国内公司生产,要么是开发板自带的:2.在ST官网ST-LINK ...

  3. mozilla/rr 调试

    http://rr-project.org/ https://github.com/mozilla/rr

  4. CTreeCtrl和CListCtrl失去焦点时高亮选中项

    设置CTreeCtrl的Always Show Selection:TrueCListCtrl的Always Show Selection:False在NM_CUSTOMDRAW事件中添加如下代码: ...

  5. Java嵌入式数据库H2学习总结(三)——在Web应用中嵌入H2数据库

    H2作为一个嵌入型的数据库,它最大的好处就是可以嵌入到我们的Web应用中,和我们的Web应用绑定在一起,成为我们Web应用的一部分.下面来演示一下如何将H2数据库嵌入到我们的Web应用中. 一.搭建测 ...

  6. The main reborn ASP.NET MVC4.0: using CheckBoxListHelper and RadioBoxListHelper

    The new Helpers folder in the project, to create the CheckBoxListHelper and RadioBoxListHelper class ...

  7. Android 数据存储04之Content Provider

    Content Provider 版本 修改内容 日期 修改人 V1.0 原始版本 2013/2/25 skywang 1 URI 通用资源标志符(Universal Resource Identif ...

  8. SQL Server 2008 安装教程

    http://www.downcc.com/tech/4135.html 序列号:Developer: PTTFM-X467G-P7RH2-3Q6CG-4DMYB

  9. eclipse 大括号 改为C语言风格

    http://lishunli.iteye.com/blog/1051701 一.原Eclipse生成的花括号情形 public class test { public static void mai ...

  10. 怎样在xcode5中使用低版本sdk,解决兼容ios7ui问题

    问题 令人头疼的是,xcode每次升级都会使用最新版本的sdk,而且只有最新版本的sdk,对之前老版本的sdk都没有默认安装,这搞的最近我很头疼, 最近我升级到Xcode5.0版本,编译后运行后,在i ...