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

MIike Eps :
   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);

Thats the updated code and still this line " GetCategoryResponseDto dto = mapper.readValue(json, GetCategoryResponseDto.class);" is still causing syntax errors

Deadpool :

If below line returns JSON formatted string then you don't need any JSONParser

String output = getCategoryServiceController.myGetCategory();

ObjectMapper has readValue method that takes String and Class<T> as arguments

public <T> T readValue(String content,
          Class<T> valueType)
        throws IOException,
               JsonParseException,
               JsonMappingException

You can just use that method

String output = getCategoryServiceController.myGetCategory();
LOGGER.debug("output {} ", output

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

return Optional.of(dto);

Note There are lot more unnecessary lines in GetCategory, for example

Optional<GetCategoryResponseDto> optional;
org.json.simple.JSONObject json = null;

And also i see mapper is null, you might face NullPointerException if it is null

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=164627&siteId=1