欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

gson ajax 数字精度丢失问题的解决方法

程序员文章站 2024-03-05 22:05:13
ajax传输的json,gson会发生丢失,long > 15的时候会丢失0 解决方案:直接把属性为long的属性自动加上双引号成为js的字符串,这样就不会发生丢失...

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 数字精度丢失问题的解决方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。