Skip to content

Instantly share code, notes, and snippets.

@leon-lourenco
Created July 26, 2019 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leon-lourenco/bec059b38b2f5a5feb3cb5e7b1b1cf25 to your computer and use it in GitHub Desktop.
Save leon-lourenco/bec059b38b2f5a5feb3cb5e7b1b1cf25 to your computer and use it in GitHub Desktop.
Parser de JSON para response entitys em lista e em objeto
package me.fullcam.toolsapi.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.http.ResponseEntity;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class ResponseEntityParser {
private static final Logger logger = LogManager.getLogger(ResponseEntityParser.class);
public static <T> T returnJsonAsObject(Class<T> any, ResponseEntity responseEntity) {
try {
return new ObjectMapper().readValue(responseEntity.getBody().toString(), any);
} catch (IOException e) {
logger.error("Error: " + e.getMessage());
}
return null;
}
public static <T> List<T> returnJsonAsList(Class<T> any, ResponseEntity responseEntity) {
try {
Class<T[]> arrayClass =(Class<T[]>) Class.forName("[L" + any.getName() + ";");
return Arrays.asList(new ObjectMapper().readValue(responseEntity.getBody().toString(), arrayClass));
} catch (IOException | ClassNotFoundException e) {
logger.error("Error: " + e.getMessage());
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment