Parse json with Objects to model Object - Java Spring - java

I have model:
public class StudyModel {
#Id
private String ID;
private boolean isStable;
private String LastUpdate;
private MainTest test;
public static class MainTest {
private String test1;
private String test2;
}
}
I want to parse it to my model.
It works correctly but when it goes to MainTest where on json file I have couple values it fails and I have null on the rest of fields.
How I can deal with it?
public StudyModel getStudyDetails(String studyId){
RestTemplate restTemplate = new RestTemplate();
String url = URL + "studies/" + studyId;
ResponseEntity<String> serverResponse = restTemplate.getForEntity(url, String.class);
Gson g = new Gson();
String json = serverResponse.getBody();
StudyModel study = g.fromJson(json, StudyModel.class);
return study;
}

RestTemplate can handle deserialization for you
ResponseEntity<StudyModel> serverResponse = restTemplate.getForEntity(url, StudyModel.class);
StudyModel studyModel = serverResponse.getBody();

Related

How to fix null values from converting JSON to POJO using Gson

I am trying to get a response message to a POJO class that has already been defined. However, I am getting null values for all the fields in the POJO class. I printed the json file and they are not null and I am wondering what is actually going. This is the response that I get.
I should get this VirtualAccountResponseDto(account_number=null, bank_code=null, unique_id=null, account_name=null, account_reference=null, bank_name=null, created_at=null, currency=null, id=null, account_status=null, customer=null)
This is the gson class that I printed to the console
+++++++++>>>>>>>>>{"data":{"account_number":"1110006278","bank_code":"000","unique_id":"KPY-VA-NEBOrKvKCmTSOJe","account_name":"James Bond","account_reference":"xyz163ath285","bank_name":"test","created_at":"2022-11-27T23:38:36.449Z","currency":"NGN","id":6268,"account_status":"active","customer":{"name":"James Bond","email":"hey#yxc.com"}},"message":"Virtual bank account created successfully","status":true}
This is what the POJO class looks like
#Data
#Builder
#AllArgsConstructor
#NoArgsConstructor
public class VirtualAccountResponseDto {
#SerializedName("account_number")
private String account_number;
#SerializedName("bank_code")
private String bank_code;
private String unique_id;
private String account_name;
private String account_reference;
private String bank_name;
private String created_at;
private String currency;
private String id;
private String account_status;
private Customer customer;
This is the customer class
#Data
public class Customer {
private String email;
private String name;
}
Here is my code to convert from Json to POJO
Gson gson = new Gson();
String requestJson = gson.toJson(bankDto);
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "Bearer "+KORAPAY_TOKEN);
headers.put("accept", "application/json");
HttpResponse<JsonNode> apiResponse = Unirest.post(KORAPAY_BASE_URL +
"virtual-bank-account")
.headers(headers)
.body(requestJson)
.asJson();
System.out.println(apiResponse.getBody());
JSONObject responseJson = apiResponse.getBody().getObject();
System.out.println("This is the response body" + apiResponse.getBody());
JsonParser jsonParser = new JsonParser();
JsonObject gsonObject = (JsonObject)jsonParser.parse(responseJson.toString());
System.out.println("+++++++++>>>>>>>>>" + gsonObject);
VirtualAccountResponseDto responseDTO = gson.fromJson(gsonObject,
VirtualAccountResponseDto.class);
System.out.println("I should get this " + responseDTO);
return responseDTO;
I have tried annotating the variable names with #Serializedname. I have also checked for case_senstivity issues. Also, I have rearranged the POJO fields in the order in which the JSON is returned and I still get the same null values
As #Marcono1234 pointed out, your DTO structure and JSON structures do not match.
I tried by modifying the structure of the DTO class to add a 'data' element and it works fine after that.
#Data
#Builder
#AllArgsConstructor
#NoArgsConstructor
public class VirtualAccountResponseDto {
DataClass data; // <-- Added this class to match the JSON structure
}
#Data
class DataClass {
private String account_number;
private String bank_code;
private String unique_id;
private String account_name;
private String account_reference;
private String bank_name;
private String created_at;
private String currency;
private String id;
private String account_status;
private Customer customer;
}
#Data
class Customer {
private String email;
private String name;
}
Output after the change:
VirtualAccountResponseDto(data=DataClass(account_number=1110006278, bank_code=000, unique_id=KPY-VA-NEBOrKvKCmTSOJe, account_name=James Bond, account_reference=xyz163ath285, bank_name=test, created_at=2022-11-27T23:38:36.449Z, currency=NGN, id=6268, account_status=active, customer=Customer(email=hey#yxc.com, name=James Bond)))

Spring RestTemplate PUT with parameters

I want to call another spring boot on spring boot
I read a lot of articles
Spring RestTemplate GET with parameters
Spring RestTemplate
Many more...
Temporary methods that I can currently use
final String uri = "http://127.0.0.1:8888/key";
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(uri)
.queryParam("id", "1234")
.queryParam("model", "model")
.queryParam("name", "name")
.queryParam("description", "description")
.queryParam("status", 0)
.queryParam("mode", 1)
.queryParam("creationDate", "2021/05/24 12:34:56")
.queryParam("updatedDate", "2021/05/24 12:34:56");
HttpEntity<?> entity = new HttpEntity<>(headers);
HttpEntity<String> response = restTemplate.exchange(
builder.toUriString(),
HttpMethod.PUT,
entity,
String.class);
I want to be able to use the class directly instead of slowly entering all the parameters
public class DataDto {
private String id;
private String model;
private String name;
private String description;
private int status;
private int mode;
private String creationDate;
private String updatedDate;
...
}
How can I use the entire class as a parameter at once?
I have tried many similar things, but there are no parameters on my server:
logger.info("getId:" + dataDto.getId());
final String uri = "http://127.0.0.1:8888/key";
RestTemplate restTemplate = new RestTemplate();
restTemplate.put(uri, DataDto.class, dataDto);
Try something like below.
Override toString() method for DataDto
#Override
public String toString() {
return String.format("id=%s&" +
"model=%s&" +
"name=%s&" +
"description=%s&" +
"status=%s&" +
"mode=%s&" +
"creationDate=%s&" +
"updatedDate=%s", id, model, name, description, status, mode,
creationDate, updatedDate);
}
Formulate URL like below,
final String uri = String.format("%s?%s", "http://127.0.0.1:8888/key", dataDto.toString())

Spring RestTemplate postForEntity returns Null Objects

I'm new to Spring and I'm having trouble consuming an API and serialising the Response to Java POJOs using Jackson. This the API endpoint I'm trying to consume.
This what my request looks like:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.set("Authorization", "Bearer " + applicationProperties.getApiKey());
ArrayList<String> externalIds = new ArrayList<>();
externalIds.add(userId);
Map<String, Object> parameters = new HashMap<>();
parameters.put("external_ids", externalIds);
HttpEntity<Map<String, Object>> request = new HttpEntity<>(parameters, headers);
ResponseEntity<ProfileExportDTO> response = this.restTemplate.postForEntity(url, request , ProfileExportDTO.class);
This is my POJO class (setters and getters removed for simplicity):
#JsonIgnoreProperties(ignoreUnknown = true)
public class ProfileExportDTO implements Serializable {
#JsonProperty("first_name")
private String firstname;
#JsonProperty("last_name")
private String lastname;
private String language;
private String email;
private String dob;
#JsonProperty("home_city")
private String city;
private String country;
private String phone;
#JsonProperty("time_zone")
private String timezone;
#JsonProperty("last_coordinates")
private float[] lastCoordinates;
private String gender;
#JsonProperty("total_revenue")
private float revenue;
private String attributed_campaign;
private String attributed_source;
private String attributed_adgroup;
private String push_subscribe;
private String email_subscribe;
My problem is that when this runs the produced object is null. Does anyone know why?

Spring Boot: Json Response is not Mapping to Entity

I am trying to map this Json response I consume through a secured RESTful API; however, the mapping is for some reason not happening correctly as I keep getting a NULL response instead of populated object.
This is my entity:
#JsonTypeName("order")
#JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT ,use = JsonTypeInfo.Id.NAME)
public class Order {
#JsonProperty("id")
private long customerd;
#JsonProperty("email")
private String customeEmail;
public long getCustomerd() {
return customerd;
}
public void setCustomerd(long customerd) {
this.customerd = customerd;
}
public String getCustomeEmail() {
return customeEmail;
}
public void setCustomeEmail(String customeEmail) {
this.customeEmail = customeEmail;
}
}
This is my service method:
public Order orderDetails (#RequestBody Order order){
String username = "username";
String password = "password";
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(username, password);
// request url
String url = "https://test.myshopify.com/admin/orders/2013413015655.json";
RestTemplate restTemplate = new RestTemplate();
HttpEntity request = new HttpEntity(headers);
ResponseEntity<Order> response = restTemplate.exchange(
url, HttpMethod.GET, request, Order.class);
return order;
}
This is my Controller Method:
#GetMapping("/orderdetails")
#ResponseStatus(HttpStatus.FOUND)
public Order getBasicAut(Order order){
return basicAuth.orderDetails(order);
}
You should configure your REST to produce the JSON content
#GetMapping(path = "/orderdetails", produces = {MediaType.APPLICATION_JSON_VALUE})
Specifically, those codes below work well
#RestController
public class JsonController {
#GetMapping(path = "/orderdetails", produces = {MediaType.APPLICATION_JSON_VALUE})
#ResponseStatus(HttpStatus.FOUND)
public Order sendJsonBack() {
final Order order = new Order();
order.setCustomerd(123L);
order.setCustomeEmail("mail#gmail.com");
return order;
}
}
#Data
class Order implements Serializable {
private static final long serialVersionUID = -4258392267221190600L;
#JsonProperty("id")
private long customerd;
#JsonProperty("email")
private String customeEmail;
}
The issue was with what my methods were returning. They both have to return a ResponseEntity of type Order as in:
public ResponseEntity<Order> orderDetails (#RequestBody Order order){
String username = "username";
String password = "password";
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(username, password);
// request url
String url = "https://test.myshopify.com/admin/orders/2013413015655.json";
RestTemplate restTemplate = new RestTemplate();
HttpEntity request = new HttpEntity(headers);
ResponseEntity<Order> response = restTemplate.exchange(
url, HttpMethod.GET, request, Order.class);
return response;
}
And my Controller to:
#GetMapping("/orderdetails")
#ResponseStatus(HttpStatus.FOUND)
public ResponseEntity<Order> getBasicAut(Order order){
return basicAuth.orderDetails(order);
}

JSON conversion error from java Pojo

I have userDTO like below, and
I am trying to convert userDTO to json string and calling rest API endpoint from my Controller, but the called rest API end point throws error as "data" is not valid JSONobject
public class UserDTO {
private String userId;
private String firstname;
private String lastname;
private List<Order> orders;
some more data member plus // setter / Getters
}
My controller class:- [converting userDTO to json string]
public class OrderController {
UserDTO userRecord = new UserDTO ();
// userRecord some values here
final HttpStatus httpStatus;
HttpEntity<?> httpEntity;
final HttpHeaders headers = new HttpHeaders();
final ObjectMapper mapper = new ObjectMapper();
headers.setContentType(MediaType.APPLICATION_JSON);
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
String jsonInput;
// I guess this is the point creating that issue. May be Im doing in wrong way....
jsonInput = mapper.writeValueAsString(new JSONObject().put("data",userRecord ));
httpEntity = new HttpEntity<Object>(jsonInput, headers);
// calling the rest API endpoint
ResponseEntity<String> responseEntity = restTemplate.exchange(
URL, HttpMethod.POST, httpEntity,
String.class,someId);
}
Server Sinippet:-
public MicroserviceResponse createOrder(#PathVariable("cId") final String cId, #RequestBody final String requestBody) throws Exception {
ObjectMapper mapper = new ObjectMapper();
requestJSON = new JSONObject(requestBody).getJSONObject("data");
final String jsonData = requestJSON.toString();
UserDTO orderSource = mapper.readValue(jsonData,
UserDTO .class);
}
Problem:-
Called API [server] throws "data is not valid JSONObject. Am i missing something here ? please guide me.
Trying to send below kind of JSON format
{
"data":{
"username":"test",
"orderId": "123097R",
"firstName":"xydz",
"lastName":"xyzd",
"email":"xx#gmail.com"
}
}
As there are no detailed server logs provided - I assume that the mentioned error is happening at the REST layer.
Please try this - create a payload Java class:
public class RestPayload implements java.io.Serializable {
private UserDTO data;
public UserDTO getUserDTO (){
return this.data;
}
public void setUserDTO(UserDTO data){
this.data = data;
}
}
And then modify your current rest operation to :
#POST
public MicroserviceResponse createOrder(#PathVariable("cId") final String cId, #RequestBody final RestPayload restPayload ) throws Exception {
UserDTO orderSource = restPayload.getUserDTO();
}
UPDATE:
You can also play with the raw JSON and modify the values according to your needs.
Try this - the below code shows how to add "data" as a parent object to the UserDTO :
Gson gson = new Gson();
JsonElement userDtoJsonElement = gson.toJsonTree(userDTO);
JsonObject dataObject = new JsonObject();
dataObject.add("data", userDtoJsonElement);
System.out.println(gson.toJson(dataObject));

Categories

Resources