Java JSON 解析错误:ClassCastException: java.util.LinkedHashMap cannot be cast to com.bonoon.common.core.domain.entity.SysUser
{
"title":"Java JSON 解析错误:ClassCastException: java.util.LinkedHashMap cannot be cast to com.bonoon.common.core.domain.entity.SysUser",
"description":"本文将介绍如何在Java中解决将JSON对象转换为SysUser对象时遇到的ClassCastException错误,并提供详细的代码示例。",
"keywords":"Java, JSON, ClassCastException, LinkedHashMap, SysUser, 解析错误, 解决方法",
"content":""{"id":15,"user":{"userName":"M0016701","phonenumber":"15914759321","email":" ","nickName":"长布镇人员","password":"M0016701","sex":"0","status":"0"}}"\n后端接受格式\n public AjaxResult addUser(@Validated @RequestBody JSONObject object) {\n Long id=(Long) object.get("id");\n SysUser user = (SysUser)object.get("user");\n前端这样传输json格式,后端使用jsonobject对象接受报错如何处理?\nClassCastException: java.util.LinkedHashMap cannot be cast to com.bonoon.common.core.domain.entity.SysUser\n\nThe error is occurring because the JSON object is being cast to the wrong type. Instead of casting it to SysUser, it is being cast to LinkedHashMap.
\nTo fix this issue, you need to convert the JSON object to the SysUser object manually. Here's an example of how you can do it: \n\njava\npublic AjaxResult addUser(@Validated @RequestBody JSONObject object) {\n Long id = (Long) object.get(\"id\");\n JSONObject userObject = (JSONObject) object.get(\"user\");\n\n SysUser user = new SysUser();\n user.setUserName(userObject.getString(\"userName\"));\n user.setPhonenumber(userObject.getString(\"phonenumber\"));\n user.setEmail(userObject.getString(\"email\"));\n user.setNickName(userObject.getString(\"nickName\"));\n user.setPassword(userObject.getString(\"password\"));\n user.setSex(userObject.getString(\"sex\"));\n user.setStatus(userObject.getString(\"status\"));\n\n // Rest of the code...\n}\n\n\nIn this code, the userObject is extracted from the JSON object, and its properties are used to set the corresponding properties of the SysUser object manually.
原文地址: https://www.cveoy.top/t/topic/qscf 著作权归作者所有。请勿转载和采集!