gson ajax 數(shù)字精度丟失問題的解決方法
ajax傳輸?shù)膉son,gson會(huì)發(fā)生丟失,long > 15的時(shí)候會(huì)丟失0
解決方案:直接把屬性為long的屬性自動(dòng)加上雙引號(hào)成為js的字符串,這樣就不會(huì)發(fā)生丟失了,ajax自動(dòng)識(shí)別為字符串。
用法:
ajaxResult("",0,new Object()); //隨便一個(gè)對(duì)象就可以,List 之類的
/** * 以Ajax方式輸出常規(guī)操作結(jié)果 * * @param status * 返回狀態(tài),200表示成功, 500表示錯(cuò)誤 * @param message * 操作結(jié)果描述 * @param tag * 附加數(shù)據(jù) * @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方法轉(zhuǎn)換json串到實(shí)體類出錯(cuò)", e); } return obj; } /** * 如果 Long 的數(shù)字超過15位,轉(zhuǎn)換為String,在json中數(shù)字兩邊有引號(hào) * @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 數(shù)字精度丟失問題的解決方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
ArrayList和LinkedList區(qū)別及使用場(chǎng)景代碼解析
這篇文章主要介紹了ArrayList和LinkedList區(qū)別及使用場(chǎng)景代碼解析,小編覺得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01SpringBoot實(shí)現(xiàn)前端驗(yàn)證碼圖片生成和校驗(yàn)
這篇文章主要為大家詳細(xì)介紹了SpringBoot實(shí)現(xiàn)前端驗(yàn)證碼圖片生成和校驗(yàn),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-02-02一篇文章帶你了解JAVA面對(duì)對(duì)象應(yīng)用
Java是一門面向?qū)ο蟮恼Z言。對(duì)象是Java程序中的基本實(shí)體。除了對(duì)象之外Java程序同樣處理基本數(shù)據(jù)。下面這篇文章主要給大家總結(jié)了關(guān)于Java中面向?qū)ο蟮闹R(shí)點(diǎn),需要的朋友可以參考借鑒,下面來一起看看吧2021-08-08SpringBoot自動(dòng)重啟、熱啟動(dòng)方式
這篇文章主要介紹了SpringBoot自動(dòng)重啟、熱啟動(dòng)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03