为了账号安全,请及时绑定邮箱和手机立即绑定

如何将对象的 json 数组对象转换为该对象的 java 8 可选列表

如何将对象的 json 数组对象转换为该对象的 java 8 可选列表

扬帆大鱼 2023-08-09 15:50:30
 public Optional<GetCategoryResponseDto> GetCategory(AppUser foundUser) throws Exception {        Optional<GetCategoryResponseDto> optional;        JSONParser parser = new JSONParser();        org.json.simple.JSONObject json;        //fix for lazy user details not loaded        if (foundUser.getAppUserDetail() == null) {            foundUser = appUserService.findByID(foundUser.getId()).orElseThrow(() -> new ModelNotFoundException("Invalid user"));        }        LOGGER.debug("foundUser {} ", gson.toJson(foundUser.getAppUserDetail().getPhoneNumber()));        String output = getCategoryServiceController.myGetCategory();        LOGGER.debug("output {} ", output);        json = (JSONObject) parser.parse(output);        ObjectMapper mapper = new ObjectMapper();        GetCategoryResponseDto dto = new GetCategoryResponseDto();        dto = mapper.readValue((DataInput) json, GetCategoryResponseDto.class);        return Optional.of(dto);这就是更新后的代码,仍然是这一行“ GetCategoryResponseDto dto = mapper.readValue(json, GetCategoryResponseDto.class);” 仍然导致语法错误
查看完整描述

1 回答

?
湖上湖

TA贡献2003条经验 获得超2个赞

如果下面的行返回 JSON 格式的字符串,那么你不需要任何JSONParser


String output = getCategoryServiceController.myGetCategory();

ObjectMapper具有readValue采用String和Class<T>作为参数的方法


public <T> T readValue(String content,

          Class<T> valueType)

        throws IOException,

               JsonParseException,

               JsonMappingException

你可以只使用该方法


String output = getCategoryServiceController.myGetCategory();

LOGGER.debug("output {} ", output


GetCategoryResponseDto dto = mapper.readValue(json, GetCategoryResponseDto.class


return Optional.of(dto);

注意中有很多不必要的行GetCategory,例如


Optional<GetCategoryResponseDto> optional;

org.json.simple.JSONObject json = null;

我还看到mapper它为空,NullPointerException如果它为空,您可能会面临


查看完整回答
反对 回复 2023-08-09
  • 1 回答
  • 0 关注
  • 66 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信