N
N
nuclear_kote2021-06-22 15:10:33
Java
nuclear_kote, 2021-06-22 15:10:33

How to disable field deserialization in jackson?

@Data
public class TestObject {

    private String name;
    @JsonRawValue
    private String result;

}

@RestController
@RequestMapping("test")
public class TestController {

    @GetMapping
    public String get() {
        return "{" +
                "\"name\": \"vasya\"," +
                "\"result\": {\"bla\": \"bla\"}" +
                "}";
    }
}


    public static void main(String[] args) {
        RestTemplate template = new RestTemplate();
        ResponseEntity<TestObject> exchange = template.exchange("http://localhost:8080/test", HttpMethod.GET, null, TestObject.class);

        System.out.println(exchange.getBody());
    }
}


you need json as a string in the result field. I cannot change the controller response (for example, wrap it in quotes). this is necessary because different data types can be transferred there, and not just json.

and now it's flying
Exception in thread "main" org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Can not deserialize instance of java.lang.String out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
nuclear_kote, 2021-06-22
@nuclear_kote

it happened

@Data
public class TestObject {

    private String name;
    @JsonDeserialize(using = ResultDeserializer.class)
    private String result;

    public static class ResultDeserializer extends JsonDeserializer<String>  {

        @Override
        public String deserialize(JsonParser jp, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
            ObjectMapper mapper = (ObjectMapper) jp.getCodec();
            JsonNode node = mapper.readTree(jp);
            return mapper.writeValueAsString(node);
        }
    }

}

D
Dmitry Roo, 2021-06-22
@xez

It's not entirely clear what you need...
@JsonIgnoremaybe it will help?...

O
Orkhan, 2021-06-22
Hasanly @azerphoenix

you need json as a string in the result field. I cannot change the controller response (for example, wrap it in quotes).

You can write your own custom converter for the controller.
https://stackoverflow.com/questions/57536693/how-t...
Or do you mean:
JsonIgnore annotation?
https://www.tutorialspoint.com/jackson_annotations...
https://stackoverflow.com/questions/12505141/only-...
There are more annotations
https://www.baeldung.com/jackson-bidirectional-rel. ..

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question