0

I have a json String and it needs to be converted to Optional data type.

Getting Optional.empty as the response. Is it possible to get the Optional here with the correct value.

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.sams.interceptor.model.mixins.HttpStatusMixIn;
import com.sams.interceptor.model.mixins.ResponseEntityMixin;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.io.IOException;
import java.util.Optional;

public class App2 {

    public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = "{\"value\":{\"id\":123}}";
        Optional<Student> abc = objectMapper.readValue(jsonStr,java.util.Optional.class);
        System.out.println(abc);
    }

}

class Student {
    int id;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}
  • That looks like an [XY-problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). First of all, `Optional` was **not** designed for such use cases (see [Uses for Optional](https://stackoverflow.com/a/23464794/17949945)), and secondly (as a consequence) it's not possible to do you was trying to do with Jackson in a straightforward way. – Alexander Ivanchenko Nov 04 '22 at 09:16
  • Maybe you can provide a more **elaborate description** of your use-case. I.e. explain what you were intended to do with the `Optional` further? Should it be returned from the method a stored somewhere? These details would help in to provide useful feedback. – Alexander Ivanchenko Nov 04 '22 at 09:19

0 Answers0