I tried to create a generic method to read the response json but I don't like to have a generic object with many hashmaps... I don't want to specify the type. I want to get the content for Country, City, etc...
AwsProxyResponse response = get("/countries");
List<Country> countryList = (List<Country>) jsonStringToObject(response.getBody()).get("countries"); // doesn't work
protected Object jsonStringToObject(String jsonString) throws IOException {
JsonObject jsonData = new JsonObject(jsonString);
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(jsonData.toString().getBytes(), Object.class);
}
What is the proper way to get the Response data and then fetch what I need (e.g. content, totalElements, etc...)
Related
I need to send json data to a post call in java. The following is the code
my pojo class
public class Data{
#JSONProperty("clientIP")
String clientIP;
#JSONProperty("empID")
String empID;
public Data setClientIP(String clientIp){
this.clientIP = clientIp;
return this;
}
public Data setEmpID(String empId){
this.empID = empId;
return this;
}
public String toString(){ /*toString conversion*/ }
}
Filter class where am setting clientIp
public doFilter(ServletRequest request, ServletResponse response){
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String clientIP = httpServletRequest.getRemoteAddr();
Data data = new Data();
data.setClientIP(clientIP);
}
Java class where am setting other emp related data for example userId
public Emp createEmp(empId, /*other emp related data*/){
Data data = new Data();
data.setEmpID(empId);
//append clientIp to this data object
ConvertToJSON(data);
}
in another service class am converting this data to json formatted string using jackson binding. Here I want to append previously set clientIp to this data so that I can convert entire data object to json formatted string
Class where am converting java object to json
convertToJSON(Object data){
ObjectMapper mapper = new ObjectMapper();
String jsonString = null;
jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(data);
}
I need output like { clientIP: 123.123.123.123, empID: emp123 }
currently it displays { clientIP: null, empID: emp123} which is obvious
As I said in comment, one simple way is to store clienIP into session attribute in your web filter as follows:
String clientIP = httpServletRequest.getRemoteAddr();
HttpSession session = httpServletRequest.getSession();
session.setAttribute("X-CLIENT-IP", clientIP);
Then you can use request.getSession().getAttribute("X-CLIENT-IP").toString() to retrieve client IP if you have a declaration of HttpServletRequest request.
After that, you can pass it as an argument for mehtod createEmp such as
public Emp createEmp(empId, clientIp) {
Data data = new Data();
data.setClientIP(clientIp);
data.setEmpID(empId);
...
}
I need to get the list of all the films.
i am in this situation and i dont know how to manage it.
My project is divided in two smaller project. Back-end project and front-end project.
Back-end part that produce a Json that contains a list of films.
The service has this pattern
#GET
#Produce(json) // here is a particular library and it funcion correctly.
List<Film> getAllFilms
The output calling this service has this pattern:
[{"title:abc","time": 5486448}, {....}, {....}]
At the Front-end project i am using Resteasy .
I have create a class service to call the back-end and to manage the response
List<Film> film= new ArrayList<>();
try{
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target("http://localhost:8080/film");
Response response = target.request().get();
film= List<Film>) response.readEntity(Film.class);
I have an exception of this type:
javax.ws.rs.ProcessingException: org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of FILM out of START_ARRAY token
Now i am trying to understand something but there is full of material and i am loosing around.
How can i unmarshall an array to a list ?
You can use readValue method of jackson to convert it to List
public List<Film> convert(String jsonString) throws JsonParseException, JsonMappingException,
IOException {
ObjectMapper objectMapper = new ObjectMapper();
List<Film> filmList = objectMapper.readValue(
jsonString,
objectMapper.getTypeFactory().constructCollectionType(
List.class, Film.class));
return filmList;
}
i currently use Google's GSON library to serialize/deserialize rest service responses.
But i have a little problem. My response object has T response attribute.
public class IninalResponse<T> {
private int httpCode;
private String description;
private T response;
private HashMap<String,String> validationErrors;
...
}
I would like to get response attribute according to object type which i specified. At this example i specified with GetAccessTokenResponse to deserialize T response attribute in the piece of code below.
public IninalResponse getAccessToken(String apikey) {
String path = "https://sandbox-api.ininal.com/v2/oauth/accesstoken";
return doPostIninal(apikey,path,null,GetAccessTokenResponse.class);
}
GSON library successfully deserializes IninalResponse object except for T response field. Gson deserializes it as LinkedTreeMap typed object.
public <T,V> IninalResponse doPostIninal(String apikey, String path,V requestBody, T response) {
RestTemplate template = restClient.getRestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.AUTHORIZATION,apikey);
headers.add(HttpHeaders.DATE, "");
headers.add(HttpHeaders.CONTENT_TYPE, "application/json");
HttpEntity<?> request = new HttpEntity<Object>(requestBody,headers);
ResponseEntity<String> accessTokenResponse = restClient.getRestTemplate().postForEntity(path,request,String.class);
IninalResponse<T> responseBody = new IninalResponse<T>();
responseBody = new Gson().fromJson(accessTokenResponse.getBody(),responseBody.getClass());
System.out.println(accessTokenResponse);
return responseBody;
}
Still i have no idea why gson could not deserialize ? What exactly am i missing ?
Due to Java's type erasure, you need to make a trick to serialize/deserialize generic types:
Type fooType = new TypeToken<IninalResponse<TheType>>() {}.getType();
gson.fromJson(accessTokenResponse.getBody(), fooType);
where TheType is the type you passed in during serialization (String I suppose).
Serialization goes as this:
Type fooType = new TypeToken<IninalResponse<String>>() {}.getType(); // I assume it was a String here.
gson.toJson(someString, fooType);
I am trying to send following Integer value to server.
int mStoreArea;
I use this link as REST client.
here is Request:
RestClient client = new RestClient(my_url);
client.AddParam("area", String.valueOf(c.getStoreArea()));
and the Error I face is : Int value required!
I retrieve this integer from a json object saved to a file, its procedure is described below:
public myClass(JSONObject json) throws JSONException {
mStoreArea = json.optInt(JSON_TAG);
}
public JSONObject toJSON() throws JSONException {
JSONObject json = new JSONObject();
json.put(JSON_TAG, mStoreArea);
return json;
}
I think you should use this:
client.AddParam("area", Integer.parseInt(c.getStoreArea()));
#GET
#Produces(MediaType.APPLICATION_JSON)
public List<ProductData> getAllProductList(#QueryParam("hotel_id") int hotel_id) throws SQLException{
System.out.println("Hotel id id==="+hotel_id);
ProductData productData=new ProductData();
List<ProductData> products = new ArrayList<ProductData>();
rs=stmt.executeQuery("select * from products where hotel_id="+hotel_id);
while(rs.next()){
productData.setProductName(rs.getString("name"));
productData.setProductCategory(rs.getString("category"));
productData.setProductRate(rs.getDouble("rate"));
productData.setProductLogoPath(rs.getString("productLogoPath"));
products.add(productData);
}
return products;
}
I have passed List as JsonObject.Now i tried to get List value like
void handleResponse(String response) throws JSONException {
JSONObject jsonObject=new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("products");
}
but i can't get the List value.anyBody can help me?
There is the simple way to convert json string to object :
Try this :
ObjectMapper mapper = new ObjectMapper();
POJO obj = mapper.readValue(yourJSONString, POJO.class);
Use method signature something similar like-
public Response getAllProduct..
&
return like-
return Response.status(Status.OK).entity(products).build();
For intg. layer use-
public ClientResponse<> similarSignatureMethod..
&
call via the client and then get response entity as-
clientResponse.getEntity();