Map json using jackson

0

I have a question on how to map a json to a model, I really have no idea which side to go to, I saw some material on the internet, but what I really lack is to really understand how it works there on the jackson part. my code is below, who can help.

ZenviaRequest

@JsonIgnoreProperties(ignoreUnknown = true)
public class ZenviaRequest {

@JsonProperty("id")
private String id;
@JsonProperty("from")
private String from;
@JsonProperty("to")
private String to;
@JsonProperty("msg")
private String msg;
@JsonProperty("schedule")
private String schedule;
@JsonProperty("callbackOption")
private String callbackOption;
@JsonProperty("aggregateId")
private String aggregateId;
@JsonProperty("flashSms")
private boolean flashSms;

//todos os getters and setters
}

ZenviaResponse

@JsonIgnoreProperties(ignoreUnknown = true)
public class ZenviaResponse {

    @JsonProperty("statusCode")
    private String statusCode;
    @JsonProperty("statusDescription")
    private String statusDescription;
    @JsonProperty("detailCode")
    private String detailCode;
    @JsonProperty("detailDescription")
    private String detailDescription;
    @JsonProperty("mobileOperatorName")
    private String mobileOperatorName;
    @JsonProperty("received")
    private String received;

    //todos os getters and setters
    }

My call

public void senderMulti(List<ZenviaRequest> zenvia) {

   //pego a lista que recebi e faço aqui toda lógica para gerar uma String Full

    Response response = null;
    try {

        Client client = ClientBuilder.newClient();
        Entity payload = Entity.json(full); // <-----

        response = client.target("https://api-rest.zenvia360.com.br/services/send-sms-multiple")
                .request(MediaType.APPLICATION_JSON_TYPE)
                .header("Authorization", "Basic ***************")
                .header("Accept", "application/json")
                .post(payload);

        System.out.println("status: " + response.getStatus());
        System.out.println("headers: " + response.getHeaders());
        System.out.println("body:" + response.readEntity(String.class));

        // aqui meu codigo desanda, não sei oque fazer aqui
        ObjectMapper mapper = new ObjectMapper();
        String jsonInString = response.readEntity(String.class);

        List<ZenviaResponse> objList = mapper.readValue(jsonInString, new TypeReference<List<ZenviaResponse>>(){});

        response.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

The return of Json

status: 200
headers: {Server=[Jetty(9.2.9.v20150224)], Connection=[close], Date=[Tue, 17 Apr 2018 00:01:51 GMT], Content-Type=[application/json]}
body:{
  "sendSmsMultiResponse" : {
"sendSmsResponseList" : [ {
  "statusCode" : "10",
  "statusDescription" : "Error",
  "detailCode" : "080",
  "detailDescription" : "Message with same ID already sent"
}, {
  "statusCode" : "10",
  "statusDescription" : "Error",
  "detailCode" : "080",
  "detailDescription" : "Message with same ID already sent"
}, {
  "statusCode" : "10",
  "statusDescription" : "Error",
  "detailCode" : "080",
  "detailDescription" : "Message with same ID already sent"
} ]
  }
}

It's all beautiful there, but how do I consume it for a ZenviaResponse List, if anyone can help me, I really appreciate it.

Trying with this code now I get this error below.

java.lang.IllegalStateException: Entity input stream has already been closed.
    at org.glassfish.jersey.message.internal.EntityInputStream.ensureNotClosed(EntityInputStream.java:225)
    at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:832)
    at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:785)
    at org.glassfish.jersey.client.ClientResponse.readEntity(ClientResponse.java:267)
    at org.glassfish.jersey.client.InboundJaxrsResponse$1.call(InboundJaxrsResponse.java:111)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:397)
    at org.glassfish.jersey.client.InboundJaxrsResponse.readEntity(InboundJaxrsResponse.java:108)
    at br.com.trendplataform.rotas.ZenviaSender.senderMulti(ZenviaSender.java:122)
    at testando.main(testando.java:52)
    
asked by anonymous 17.04.2018 / 02:44

1 answer

0

The readEntity(Class<T> entityType) method can only be used once per response, since when it is executed, the input stream is consumed and the connection is closed (if the response is read as a < in> input stream , it should be closed for the connection to be either.)

In your code, it is being invoked twice in the following snippets:

System.out.println("body:" + response.readEntity(String.class));

E:

String jsonInString = response.readEntity(String.class);

To prevent the exception from occurring, reverse the order of the above lines and pass the variable jsonInString as argument to the println method:

String jsonInString = response.readEntity(String.class);
System.out.println("body: " + jsonInString);

As for using mapping, you need to make your class match the JSON format. So you should have the following classes:

SendSmsMultiResponse:

public class SendSmsMultiResponse {

    @JsonProperty("sendSmsMultiResponse")
    private SendSmsMultiResponseList sendSmsMultiResponse;

    //getters e setters
}

SendSmsMultiResponseList:

public class SendSmsMultiResponseList {

    @JsonProperty("sendSmsResponseList")
    private List<SendSmsResponse> sendSmsResponseList;

    //getters e setters
}

SendSmsResponse:

public class SendSmsResponse {

    @JsonProperty("statusCode")
    private String statusCode;
    @JsonProperty("statusDescription")
    private String statusDescription;
    @JsonProperty("detailCode")
    private String detailCode;
    @JsonProperty("detailDescription")
    private String detailDescription;

    //getters e setters
}

And, to deserialize JSON:

ObjectMapper mapper = new ObjectMapper();
SendSmsMultiResponse sendSmsMultiResponse = mapper.readValue(jsonInString, SendSmsMultiResponse.class);

Obs : Jackson can be integrated into Jersey using the jersey-media-json-jackson pendency dependency (which must be in the same Jersey version as that used), no additional configuration is required. If you add it, you could read the entity directly from the response this way:

response.readEntity(SendSmsMultiResponse.class);
    
17.04.2018 / 15:24