ajax传输的json,gson会发生丢失,long > 15的时候会丢失0

解决方案:直接把属性为long的属性自动加上双引号成为js的字符串,这样就不会发生丢失了,ajax自动识别为字符串。

用法:

ajaxResult("",0,new Object()); //随便一个对象就可以,List 之类的

  1. /**
  2. * 以Ajax方式输出常规操作结果
  3. *
  4. * @param status
  5. * 返回状态,200表示成功, 500表示错误
  6. * @param message
  7. * 操作结果描述
  8. * @param tag
  9. * 附加数据
  10. * @return
  11. */
  12. protected ActionResult ajaxResult(int status, final String message, Object tag) {
  13. JsonObject json = new JsonObject();
  14. json.addProperty("status", status);
  15. json.addProperty("message", message);
  16. String strJson = json.toString();
  17. if (tag != null) {
  18. StringBuffer sb = new StringBuffer();
  19. sb.append(strJson.substring(0, strJson.length() - 1));
  20. sb.append(",\"tag\":");
  21. sb.append(GsonUtils.toJsonWithGson(tag));
  22. sb.append("}");
  23. strJson = sb.toString();
  24. }
  25. return writeJson(strJson);
  26. }
  27. /**
  28. * 向客户端输出文本信息
  29. *
  30. * @param message
  31. * @return
  32. */
  33. protected ActionResult write(final String message) {
  34. return new ActionResult() {
  35. @Override
  36. public void render(BeatContext arg0) throws Exception {
  37. beat.getResponse().setCharacterEncoding("UTF-8");
  38. beat.getResponse().setContentType("text/json;charset=UTF-8");
  39. PrintWriter out = beat.getResponse().getWriter();
  40. out.print(message);
  41. out.close();
  42. }
  43. };
  44. }
  45. /**
  46. * 向客户端输出文本信息
  47. *
  48. * @param message
  49. * @return
  50. */
  51. protected ActionResult writeText(final String message) {
  52. return new ActionResult() {
  53. @Override
  54. public void render(BeatContext arg0) throws Exception {
  55. beat.getResponse().setCharacterEncoding("UTF-8");
  56. beat.getResponse().setContentType("application/text");
  57. PrintWriter out = beat.getResponse().getWriter();
  58. out.print(message);
  59. out.close();
  60. }
  61. };
  62. }

GsonUtils.java


  1. package com.xxx.xxx.common.util.gson;
  2. import com.google.gson.*;
  3. import java.lang.reflect.Type;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6. import java.util.Map;
  7. public class GsonUtils {
  8. //private static Log logger = LogFactory.getLog(GsonUtils.class);
  9. public static String toJsonWithGson(Object obj) {
  10. Gson gson = createGson(); //new Gson();
  11. return gson.toJson(obj);
  12. }
  13. public static String toJsonWithGson(Object obj, Type type) {
  14. Gson gson = createGson(); //new Gson();
  15. return gson.toJson(obj, type);
  16. }
  17. @SuppressWarnings("unchecked")
  18. public static String toJsonWithGson(List list) {
  19. Gson gson = createGson(); //new Gson();
  20. return gson.toJson(list);
  21. }
  22. @SuppressWarnings("unchecked")
  23. public static String toJsonWithGson(List list, Type type) {
  24. Gson gson = createGson(); //new Gson();
  25. return gson.toJson(list, type);
  26. }
  27. public static String toJsonWithGsonBuilder(Object obj) {
  28. Gson gson = new GsonBuilder().setExclusionStrategies(new MyExclusionStrategy()).serializeNulls().create();
  29. return gson.toJson(obj);
  30. }
  31. public static String toJsonWithGsonBuilder(Object obj, Type type) {
  32. Gson gson = new GsonBuilder().setExclusionStrategies(new MyExclusionStrategy()).serializeNulls().create();
  33. return gson.toJson(obj, type);
  34. }
  35. @SuppressWarnings("unchecked")
  36. public static String toJsonWithGsonBuilder(List list) {
  37. Gson gson = new GsonBuilder().setExclusionStrategies(new MyExclusionStrategy()).serializeNulls().create();
  38. return gson.toJson(list);
  39. }
  40. @SuppressWarnings("unchecked")
  41. public static String toJsonWithGsonBuilder(List list, Type type) {
  42. Gson gson = new GsonBuilder().setExclusionStrategies(new MyExclusionStrategy()).serializeNulls().create();
  43. return gson.toJson(list, type);
  44. }
  45. public static <T> Object fromJson(String json, Class<T> clazz) {
  46. Object obj = null;
  47. try {
  48. Gson gson = new Gson();
  49. obj = gson.fromJson(json, clazz);
  50. } catch (Exception e) {
  51. //logger.error("fromJson方法转换json串到实体类出错", e);
  52. }
  53. return obj;
  54. }
  55. /**
  56. * 如果 Long 的数字超过15位,转换为String,在json中数字两边有引号
  57. * @return
  58. */
  59. private static Gson createGson(){
  60. GsonBuilder gsonBuilder = new GsonBuilder();
  61. LongSerializer serializer = new LongSerializer();
  62. gsonBuilder.registerTypeAdapter(Long.class, serializer);
  63. gsonBuilder.registerTypeAdapter(long.class, serializer);
  64. Gson gson = gsonBuilder.create();
  65. return gson;
  66. }
  67. public static void main(String... args) throws Exception{
  68. // long a = 12345678901234578L;
  69. //
  70. // GsonBuilder builder = new GsonBuilder();
  71. // builder.registerTypeAdapter(Long.class, new LongSerializer());
  72. // Gson gson2 = builder.create();
  73. // System.out.println(gson2.toJson(a));
  74. //
  75. // Gson gson = new GsonBuilder().setExclusionStrategies(new MyExclusionStrategy()).serializeNulls().create();
  76. // String str = gson.toJson(a);
  77. // System.out.println(str);
  78. TestVO vo = new TestVO();
  79. vo.setId(618708732263538688L);
  80. vo.setId2(918708732263538688L);
  81. System.out.println(toJsonWithGson(vo));
  82. }
  83. static class LongSerializer implements JsonSerializer<Long> {
  84. public JsonElement serialize(Long src, Type typeOfSrc, JsonSerializationContext context) {
  85. if(src!=null){
  86. String strSrc = src.toString();
  87. if(strSrc.length()>15){
  88. return new JsonPrimitive(strSrc);
  89. }
  90. }
  91. return new JsonPrimitive(src);
  92. }
  93. }
  94. static class TestVO {
  95. public long getId() {
  96. return id;
  97. }
  98. public void setId(long id) {
  99. this.id = id;
  100. }
  101. private long id;
  102. public Long getId2() {
  103. return id2;
  104. }
  105. public void setId2(Long id2) {
  106. this.id2 = id2;
  107. }
  108. private Long id2;
  109. }
  110. }

MyExclusionStrategy.java


  1. package com.xxx.xxx.common.util.gson;
  2. import com.google.gson.ExclusionStrategy;
  3. import com.google.gson.FieldAttributes;
  4. public class MyExclusionStrategy implements ExclusionStrategy {
  5. private final Class<?> typeToSkip;
  6. public MyExclusionStrategy(){
  7. this.typeToSkip=null;
  8. }
  9. public MyExclusionStrategy(Class<?> typeToSkip) {
  10. this.typeToSkip = typeToSkip;
  11. }
  12. public boolean shouldSkipClass(Class<?> clazz) {
  13. return (clazz == typeToSkip);
  14. }
  15. public boolean shouldSkipField(FieldAttributes f) {
  16. return f.getAnnotation(NotSerialize.class) != null;
  17. }
  18. }

NotSerialize


  1. package com.xxx.xxx.common.util.gson;
  2. import java.lang.annotation.ElementType;
  3. import java.lang.annotation.Retention;
  4. import java.lang.annotation.RetentionPolicy;
  5. import java.lang.annotation.Target;
  6. @Retention(RetentionPolicy.RUNTIME)
  7. @Target({ElementType.FIELD})
  8. public @interface NotSerialize {
  9. }

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. CENTOS下搭建SVN服务器(转)

    1.安装svn yum install -y subversion 2.验证安装是否成功 svnserve --version 3.创建svn版本库 mkdir svn svnadmin create ...

  2. Android签名详解

    1.什么是签名?      如果这个问题不是放在Android开发中来问,如果是放在一个普通的版块,我想大家都知道签名的含义.可往往就是将一些生活中常用的术语放在计算机这种专业领域,大家就开始迷惑了. ...

  3. ZOJ 2702 Unrhymable Rhymes 贪心

    贪心.能凑成一组就算一组 Unrhymable Rhymes Time Limit: 10 Seconds      Memory Limit: 32768 KB      Special Judge ...

  4. [Office Web Apps]实现在线office文档预览

    摘要 在使用office web apps实现office文档在线预览的时候,需要注意的地方. web api web api作为owa在线预览服务回调的接口,这里面核心代码片段如下: using H ...

  5. error: internal error: unable to execute QEMU command &#39;migrate&#39;: this feature or command is not cur

    感谢朋友支持本博客,欢迎共同探讨交流,因为能力和时间有限.错误之处在所难免,欢迎指正. 假设转载.请保留作者信息. 博客地址:http://blog.csdn.net/qq_21398167 原博文地 ...

  6. 使用C#的泛型队列Queue实现生产消费模式

    本篇体验使用C#的泛型队列Queue<T>实现生产消费模式. 如果把生产消费想像成自动流水生产线的话,生产就是流水线的物料,消费就是某种设备对物料进行加工的行为,流水线就是队列. 现在,要 ...

  7. Grid布局方式

    wp7中Grid布局类似HTML中的表格,但是又不太一致! 为了测试新一个3行3列的Grid 方了方便,剔除掉其它XAML代码 [c-sharp:collapse] view plaincopy   ...

  8. C#编程(十四)----------构造函数

    原文链接:http://blog.csdn.net/shanyongxu/article/details/46501683 构造函数 所谓的构造函数就是和类名重名的且没有返回值的方法. class P ...

  9. 一键GHOST优盘版安装XP/win7系统

    系统的安装方法有各种各样,一键GHOST优盘版也是其中的一种系统安装方法,也是俗称的U盘系统安装.下面豆豆来详细介绍下使用一键GHOST优盘版系统安装方法. 一.安装: 所谓"优盘" ...

  10. window消息机制

    剖析Windows消息处理机制 前一段,帮人写了个小控件,又温习了一遍Windows消息处理机制,现在把一些知识点总结出来,供大家参考.1.窗口    Windows程序是由一系列的窗口构成的,每个窗 ...