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

 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);” 仍然导致语法错误


扬帆大鱼
浏览 105回答 1
1回答

湖上湖

如果下面的行返回 JSON 格式的字符串,那么你不需要任何JSONParserString output = getCategoryServiceController.myGetCategory();ObjectMapper具有readValue采用String和Class<T>作为参数的方法public <T> T readValue(String content,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Class<T> valueType)&nbsp; &nbsp; &nbsp; &nbsp; throws IOException,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;JsonParseException,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;JsonMappingException你可以只使用该方法String output = getCategoryServiceController.myGetCategory();LOGGER.debug("output {} ", outputGetCategoryResponseDto dto = mapper.readValue(json, GetCategoryResponseDto.classreturn Optional.of(dto);注意中有很多不必要的行GetCategory,例如Optional<GetCategoryResponseDto> optional;org.json.simple.JSONObject json = null;我还看到mapper它为空,NullPointerException如果它为空,您可能会面临
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java