Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to deal with the loss of accuracy when javascript receives long type parameters

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of how to deal with the loss of accuracy when javascript receives long type parameters, the content is detailed and easy to understand, the operation is simple and fast, and it has a certain reference value. I believe that after reading this article on how to deal with the loss of accuracy when javascript receives long type parameters, there will be some gains, let's take a look.

I. description of the problem

Recently in the transformation of the internal management system, found a huge pit, that is, the front-end JavaScript in the acquisition of back-end Long parameters, the loss of precision!

At first, it was normal to simulate interface requests with postman, but there was a problem when using browsers to request them!

Problem recurrence

@ RequestMapping ("/ queryUser") public List queryUser () {List resultList = new ArrayList (); User user = new User (); / / give a long user ID user.setId (123456789012345678L); resultList.add (user); return resultList;}

At the beginning, I really didn't find this hole, but when I was testing, I found that the ID passed from the front end to the back end was inconsistent with the ID stored in the database, and I found that JavaScript still had this sinkhole!

Due to the reason of Number type in JavaScript, the number of Long type can not be represented completely. When the length of Long is more than 17 bits, the precision will be lost.

When we change the above user ID to 19 bits, let's take a look at the result returned by the browser request.

/ / set user ID with 19-bit user.setId (1234567890123456789l)

When the returned result exceeds 17 digits, the rest becomes 0!

II. Solutions

In such a situation, what should we do?

The first way: change the long type to the String type in the background, but the cost is a little high, as long as it is involved, it needs to be changed.

The second method: use the tool to convert long type to String type, this method can achieve global conversion (recommended)

The third method: front-end processing (currently there is no good way, not recommended)

Because the project involves a lot of code, it is impossible to change the long type to the String type, and there are many ways to use the Long type, which is very risky, so it is not recommended!

The ideal way is to use the aop agent to intercept all the methods, uniformly handle the return parameters, and convert them using tools, as follows!

2.1.The Jackson tool serializes objects

We can use the Jackson toolkit to serialize objects.

First add the necessary dependencies to the maven

Com.fasterxml.jackson.core jackson-core 2.9.8 com.fasterxml.jackson.core jackson-annotations 2.9.8 com.fasterxml.jackson.core jackson-databind 2.9.8

Write a conversion tool class JsonUtil

Public class JsonUtil {private static final Logger log = LoggerFactory.getLogger (JsonUtil.class); private static ObjectMapper objectMapper = new ObjectMapper (); private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; all fields of static {/ / object are listed in objectMapper.setSerializationInclusion (JsonInclude.Include.ALWAYS); / / default conversion of timestamps form objectMapper.configure (SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) / ignore the error objectMapper.configure from empty bean to json (SerializationFeature.FAIL_ON_EMPTY_BEANS, false); / / set to East Zone 8 objectMapper.setTimeZone (TimeZone.getTimeZone ("GMT+8")); / / uniform date format objectMapper.setDateFormat (new SimpleDateFormat (DATE_FORMAT)) / / when deserializing, ignore the situation that exists in the json string, but there is no corresponding attribute in the java object, and prevent the error objectMapper.configure (DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); when the / / sequence is replaced by json, all long will be changed into string objectMapper.registerModule (new SimpleModule (). AddSerializer (Long.class, ToStringSerializer.instance) .addSerializer (Long.TYPE, ToStringSerializer.instance)) } / * object serialized to json string * @ param obj * @ param * @ return * / public static String objToStr (T obj) {if (null = = obj) {return null;} try {return obj instanceof String? (String) obj: objectMapper.writeValueAsString (obj);} catch (Exception e) {log.warn ("objToStr error:", e); return null }} / * json string deserialization into object * @ param str * @ param clazz * @ return * / public static T strToObj (String str, Class clazz) {if (StringUtils.isBlank (str) | | null = = clazz) {return null;} try {return clazz.equals (String.class)? (t) str: objectMapper.readValue (str, clazz);} catch (Exception e) {log.warn ("strToObj error:", e); return null }} / * json strings are deserialized into objects (array) * @ param str * @ param typeReference * @ param * @ return * / public static T strToObj (String str, TypeReference typeReference) {if (StringUtils.isBlank (str) | | null = = typeReference) {return null } try {return (T) (typeReference.getType () .equals (String.class)? Str: objectMapper.readValue (str, typeReference);} catch (Exception e) {log.warn ("strToObj error", e); return null;}

Next, write an entity class Person for testing

@ Datapublic class Person implements Serializable {private static final long serialVersionUID = 1L; private Integer id; / / long parameter private Long uid; private String name; private String address; private String mobile; private Date createTime;}

Finally, let's write a test class to test the effect.

Public static void main (String [] args) {Person person = new Person (); person.setId (1); person.setUid (1111L); person.setName ("hello"); person.setAddress (""); System.out.println (JsonUtil.objToStr (person));}

The output is as follows:

The most critical line of code is to register the transformation class so that all long can be changed into string.

When replacing the sequence with json, change all long to stringSimpleModule simpleModule = new SimpleModule (); simpleModule.addSerializer (Long.class, ToStringSerializer.instance); simpleModule.addSerializer (Long.TYPE, ToStringSerializer.instance); objectMapper.registerModule (simpleModule)

If you want to format a date, you can set it globally.

/ / Global uniform date format objectMapper.setDateFormat (new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss"))

Alternatively, you can set a property individually, such as formatting the createTime attribute as yyyy-MM-dd, with the following comments.

@ JsonFormat (pattern= "yyyy-MM-dd", timezone= "GMT+8") private Date createTime

After the tool conversion class is written, it is very simple. You only need to serialize the parameters returned by the method intercepted by aop, and you can automatically turn all long into string.

2.2, SpringMVC configuration

If it is a SpringMVC project, the operation is also very simple.

Customize an implementation class that inherits from ObjectMapper

Package com.example.util;/** * inherits ObjectMapper * / public class CustomObjectMapper extends ObjectMapper {public CustomObjectMapper () {super (); SimpleModule simpleModule = new SimpleModule (); simpleModule.addSerializer (Long.class, ToStringSerializer.instance); simpleModule.addSerializer (Long.TYPE, ToStringSerializer.instance); registerModule (simpleModule);}}

Add the following configuration to the configuration file of SpringMVC

Application/json;charset=UTF-8 text/plain Charset=UTF-8 2.3 、 SpringBoot configuration

If it is a SpringBoot project, the operation is similar.

Write a WebConfig configuration class, implement self-WebMvcConfigurer, and override the configureMessageConverters method

/ * WebMvc configuration * / @ Configuration@Slf4j@EnableWebMvcpublic class WebConfig implements WebMvcConfigurer {/ * add message conversion class * @ param list * / @ Override public void configureMessageConverters (List

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report