Как преобразовать объект массива json объекта в необязательный список java 8 этого объекта - PullRequest
4 голосов
/ 19 сентября 2019
   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 Ответ

1 голос
/ 19 сентября 2019

Если строка ниже возвращает строку в формате 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, если оно равно нулю

...