Skip to content
Advertisement

java model mock response json

I am creating a Rest service which calls an external service. I have this problem: the external service I call responds in two ways depending on the case of Success or Failed. This is json:

json{
    "result": "001",
    "status": "Success",
    "response": {
        "codiceCase": "CAS-46759-Q8P7X3",
        "guidCase": "88458d32-dd42-ec11-8c62-0022489d2f61"}
} 
OR 
{
    "result": "002",
    "status": "Failed",
    "errorManagement": {
        "errorCode": "E02",
        "errorDescription": "field not value in body"
    }
}

Well I created 3 simple classes:

  1. class XXX… private String result, status; …. getter & setter
  2. class Response… private String codiceCase, guidCase; … getter & setter
  3. class ErrorManagement…private String errorCode, errorDescription;… getter & setter But when I populate with my mock, the json is always formed with the class field that I don’t care for example:
{
    "result": "001",
    "status": "Success",
    "response": {
        "codiceCase": "CAS-46759-Q8P7X3",
        "guidCase": "88458d32-dd42-ec11-8c62-0022489d2f61"    },
        {
***"errorMessage"**: null}
}

How can I get only 2 of the 3 classes returned as json in my mock? Thanks for your help.

Advertisement

Answer

I suppose you’re using Jackson to deserialize JSON as this is – I think – the default for spring.

With Jackson you can annotate the model class to omit null values in the JSON string representation:

@JsonInclude(Include.NON_NULL)
public class Model { … }
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement