当前位置:网站首页>See how I store integer data in the map < string, string > set
See how I store integer data in the map < string, string > set
2022-06-26 10:26:00 【Silent discrimination】
List of articles
One 、 Antecedents feed
A few days ago, the test gave me a defect , Prompt type conversion error , But I can't figure out what the problem is with the corresponding code
1、 Defect background
Abstract the model roughly , Other colleagues put the front desk data into a map in , And then put this map To json The string is passed to the background , And then I'll put this json The string is deserialized into a map object , Finally put this map Object passed to me .
2、 The error report is as follows :
Just read the error message , In fact, I am still very happy , This is obviously a type conversion exception , It must be that I will Integer The number of type is converted to a String String of type , Keep looking down

3、 Where the code reports an error
The following method is used to locate the error location , Then I fell into a deep thought ,String turn Integer? What kind of type conversion exception are you ? I am not two String?

4、 This method is only a simple method for judging the blank

Two 、 Looking for problems
1、 Check the receiving parameters in the log
I'm glad , Fortunately, I printed the received parameters in the log . It turned out that when I typed the log, I sent it directly map, There is no custom serialization for it , So that I can't see the corresponding type of data ( It will be explained later , This data type is important ), Next time you have to remember to serialize

2、 Observe the parameters passed from the foreground to the background
but , I can only view the corresponding parameters at the front desk , Finally, I found it in the parameters of the foreground . It is found that a parameter does not look like a string

3、 Execute the judgment method again
Then I use numeric arguments to execute StringUtils.isNotBlank() Method , I can only say that this mistake is right .
But here comes a new problem :
- If it is directly digital compilation, it will not pass !
- Even if it is Object Parameters of type , I still need a forced transfer here , But my code is not forced to turn !
- Also, the parameter generic type of the method I reported an error is Map<String,String>, Generic types are limited to String Class cannot receive Integer Type parameter ! Really? ?

4、 So after reading my colleague's code , Locate the problem again
In fact, the work of colleagues is to give the receptionist json character string , Deserialize to a Map<String,String> The collection of . Then the problem can only be in this deserialization , There are still numbers when they are passed in , How come there are no numbers ?
3、 ... and 、 Verification questions
1、 Deserialize your own test
Simulate the whole process code
public class Map Generic compatibility {
public static void main(String[] args) {
// Simulate the data transmitted from the foreground to the background
Map<String, Object> map = new HashMap<>();
map.put("key1", 1);
map.put("key2", "a");
String jsonStr = "";
jsonStr = JSON.toJSONString(map);
// To the backstage json character string
System.out.println(jsonStr);
// Deserialize the string
Map<String, String> params = JSON.parseObject(jsonStr, HashMap.class);
for (Map.Entry<String, String> entry : params.entrySet()) {
if (entry.getValue() instanceof String) {
} else {
System.out.println(" Not a string type ");
}
System.out.println(entry.getValue());
}
}
}

We were surprised to find out , I didn't report a mistake , He didn't report a mistake , He didn't report a mistake ,Integer The transformation of is to String No problem , And when we finally got the data, it was still Integer type , I'm a good guy .
Then I thought about it json Deserialization is done through reflection .
2、 Reflection revalidation
It can actually , I use reflection to Map<String,String> Add data to the object of , And then traverse the map object , But I found that value It's a Integer type .
Then everything makes sense

Verification code :
public class TestReflect {
public static void main(String[] args) throws Exception {
Map<String, String> map = new HashMap<>();
Method put = map.getClass().getMethod("put", Object.class, Object.class);
put.invoke(map, "key1", 1);
put.invoke(map, "key2", "value2");
System.out.println(JSON.toJSON(map));
for (Map.Entry<String, String> entry : map.entrySet()) {
if (entry.getValue() instanceof String) {
} else {
System.out.println(" The key It's other types :" + entry.getValue().getClass());
}
}
}
}
3、 Conclusion
The final conclusion is , When colleagues transfer all the parameters of the foreground to the background , It contains a value by Integer Data of type , That analogy is put into a Map<String,Object> Of map Collection , In response to the map After serialization , It becomes an ordinary json character string .
The key to the problem lies in the position of inverse sequence , In response to the json When a string is deserialized , There's a problem . But this is a runtime exception . Because of our json The string contains Integer Parameters of type , But the deserialized object is a String type , According to the previous demonstration , When using reflection for assignment , No errors are reported , So that everything is calm .
But when we are using the corresponding parameters , Here's the problem , Because we only recognize deserialized String Type of map, But what we actually got was Integer, That led to subsequent errors .
How should we use it ?
In my opinion, if we are not sure whether there are multiple types of parameters , have access to Object Type of map Receive the set data from the inverse sequence , Do not use the forced conversion form when obtaining the corresponding parameters , Instead, use more friendly String.valueOf Get the corresponding content ( The bottom layer is to call the wrapper type toString Method )

边栏推荐
- What is LSP
- How to start the learning journey of webrtc native cross platform development?
- MySQL第十三次作业-事务管理
- Record the handling of oom problems caused by too many threads at one time
- Yarn package management tool
- MySQL第十一作業-視圖的應用
- Selection of webrtc video codec type VP8 H264 or other? (openh264 encoding, ffmpeg decoding)
- Extracting public fragments from thymeleaf
- 118. Yanghui triangle
- 2. merge two ordered arrays
猜你喜欢

创建对象的时候堆内存的分配

How to change the QR code material color of wechat applet

The IE mode tab of Microsoft edge browser is stuck, which has been fixed by rolling back the update

Write data to local file

全渠道、多场景、跨平台,App如何借助数据分析渠道流量

P1296 whispers of cows (quick row + binary search)

Problems encountered in the application and development of Hongmeng and some roast

开发者,微服务架构到底是什么?

Call API interface to generate QR code of wechat applet with different colors

SSM项目小例子,SSM整合图文详细教程
随机推荐
Small example of SSM project, detailed tutorial of SSM integration
Detailed explanation of winsorflow quantum installation process
Blog article index Summary - wechat games
Write data to local file
MySQL第十一作业-视图的应用
Jar version conflict resolution
Pytest configuration file
Openxcap usage
Retrofit common request methods and comments, post, get heard file upload
MySQL第十二次作业-存储过程的应用
【无标题】
Leetcode intermediate node of linked list
字符串常量池、class常量池和运行时常量池
Global and Chinese market of cryogenic bulk tanks 2022-2028: Research Report on technology, participants, trends, market size and share
1. sum of two numbers (leetcode topic)
方法区里面有什么——class文件、class文件常量池、运行时常量池
Full introduction to flexboxlayout (Google official flexible implementation of flow layout control)
[binary search] 4 Find the median of two positive arrays
Cloud native essay using Hana expression database service on Google kubernetes cluster
Recyclerview implements flow layout (LinearLayout with line wrap) (flexboxlayoutmanager)