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 包含加减乘除四个方法,能确保浮点数运算不丢失精度 * * 我们知道计算机编程语言里浮点数计算会存在精度丢失问题(或称舍入误差), ...
随机推荐
- STM32F4: Generating parallel signals with the FSMC
STM32F4: Generating parallel signals with the FSMC The goal: The memory controller can be used to ge ...
- .Net Discovery系列之十-深入理解平台机制与性能影响(上)
转眼间<.Net Discovery>系列文章已经推出1年了,本文为该系列的第10-13篇文章,在本文中将对以前所讲的.Net平台知识做一个小小的总结与机制分析,引出并重点介绍这些机制对程 ...
- 基于设备树的TQ2440 DMA学习(1)—— 芯片手册
作者 彭东林pengdonglin137@163.com 平台 TQ2440内核Linux4.9 概述 一直想抽时间学习一下DMA驱动,今天就以S3C2440为例,这款芯片的DMA控制器足够简单,也比 ...
- Client Dataset Basics
文章出处: http://www.informit.com/articles/article.aspx?p=24094 In the preceding two chapters, I discus ...
- Unity Shader _Time 的单位
名称 类型 说明 _Time float4 t 是自该场景加载开始所经过的时间,4个分量分别是 (t/20, t, t*2, t*3) _SinTime float4 t 是时间的正弦值,4个分量分别 ...
- cocos2d-x中CCLabelAtlas的小图片拼接
美术在设计UI时,很多界面可能使用了数字图片来展示一些效果,比如CD或者 x1/x2等,一般她们都会切成很多单张小的图片,类似这样 cocox2d-x中CCLabelAtlas支持直接从图片中读取 ...
- Easyui 搜索框的折叠与展开方法
HTML 文件: <div id="searchForm" region="north" title="XXXX查询" collaps ...
- [Web 前端] 如何在React中做Ajax 请求?
cp from : https://segmentfault.com/a/1190000007564792 如何在React中做Ajax 请求? 首先:React本身没有独有的获取数据的方式.实际上, ...
- C#与Java 的区别
相同点:都是面向对象编程的语言,都能够实现面向对象的(封装,继承,多态)思想 不同点:1. c#中的命名空间是namespace类似于Java中的package(包),在Java中导入包用impo ...
- Holt Winter 指数平滑模型
1 指数平滑法 移动平均模型在解决时间序列问题上简单有效,但它们的计算比较难,因为不能通过之前的计算结果推算出加权移动平均值.此外,移动平均法不能很好的处理数据集边缘的数据变化,也不能应用于现有数据集 ...