All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.macrocloud.kernel.toolkit.jackson.BigNumberSerializer Maven / Gradle / Ivy

There is a newer version: 1.1.0-RELEASE
Show newest version
package org.macrocloud.kernel.toolkit.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JacksonStdImpl;
import com.fasterxml.jackson.databind.ser.std.NumberSerializer;

import java.io.IOException;


/**
 * 大数值序列化,避免超过js的精度,造成精度丢失.
 *
 * @author macro
 */
@JacksonStdImpl
public class BigNumberSerializer extends NumberSerializer {

	/**
	 * js 最大值为 Math.pow(2, 53),十进制为:9007199254740992
	 */
	private static final long JS_NUM_MAX = 0x20000000000000L;
	/**
	 * js 最小值为 -Math.pow(2, 53),十进制为:-9007199254740992
	 */
	private static final long JS_NUM_MIN = -0x20000000000000L;
	/**
	 * Static instance that is only to be used for {@link java.lang.Number}.
	 */
	public final static BigNumberSerializer instance = new BigNumberSerializer(Number.class);

	/**
	 * Instantiates a new big number serializer.
	 *
	 * @param rawType the raw type
	 */
	public BigNumberSerializer(Class rawType) {
		super(rawType);
	}

	/**
	 * 

Title: serialize

*

Description:

. * * @param value the value * @param gen the gen * @param provider the provider * @throws IOException Signals that an I/O exception has occurred. * @see com.fasterxml.jackson.databind.ser.std.NumberSerializer#serialize(java.lang.Number, com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.SerializerProvider) */ @Override public void serialize(Number value, JsonGenerator gen, SerializerProvider provider) throws IOException { long longValue = value.longValue(); if (longValue < JS_NUM_MIN || longValue > JS_NUM_MAX) { gen.writeString(value.toString()); } else { super.serialize(value, gen, provider); } } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy