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

How do i convert a json array object of an object into a java 8 optional list of that object

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

如果在 returns JSON 行下方,则不需要任何 JSONParser

格式的字符串
String output = getCategoryServiceController.myGetCategory();

ObjectMapperreadValue 方法以 StringClass<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