我正在尝试将 json 字符串转换为我各自的 pojo 类。 json字符串是base64 token 的解码版本。
解码后的值是
{"userId":"1234567890","userName": "John Doe", roles: ["admin","users"]}
我正在使用代码String jsonFormat=objectMapper.writeValueAsString(decoded);
,其中解码的是上面提到的字符串。
当我尝试使用objectmapper
将其转换为对象时,出现以下错误
objectMapper.readValue(jsonFormat, PtsbUser.class);
错误:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.ptsb.rbaccomponent.models.PtsbUser` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{userId:"1234567890",userName: "John Doe", roles: ["admin","users"]}')
at [Source: (String)""{userId:\"1234567890\",userName: \"John Doe\", roles: [\"admin\",\"users\"]}\n \n \n ""; line: 1, column: 1]
我还更新了解码后的字符串,并将括号放入键中。我使用 https://www.base64encode.org/ 进行编码的 base64 它给了我 token
eyJ1c2VySWQiOiIxMjM0NTY3ODkwIiwidXNlck5hbWUiOiAiSm9obiBEb2UiLCByb2xlczogWyJhZG1pbiIsInVzZXJzIl19CiAgICAgCiAgCiAgICA=
我正在使用下面的实用程序代码来获取解码后的字符串:
Base64.getDecoder().decode(encoded);
String decripted=new String (decoded);
return decripted
最佳答案
如果数据是 bas64 编码的 json 字符串,你可以这样做:
objectMapper.readValue(Base64.getDecoder().decode(data), PtsbUser.class);
但是您的原始字符串无效 json:
{userId:"1234567890",userName: "John Doe", roles: ["admin","users"]}
这是有效的:
{"userId":"1234567890","userName": "John Doe", "roles": ["admin","users"]}
这里不需要objectMapper.writeValueAsString Method that can be used to serialize any Java value as a String
objectMapper.writeValueAsString(decoded);
因为此方法用于 java -> json
序列化,并且您已经有要反序列化的 json 字符串
关于java - 解码后将base64 token转换为jsonString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60629752/