convert xml to Java object using jackson - java

I want to convert XML to JSON using Jackson library. I have tried below code to get Json as below using jackson but I can't. if I tried using json, I can but I want to know how to do with Jackson library.
#RequestMapping(value="/convertXMLtoJson",method=RequestMethod.POST,consumes = MediaType.APPLICATION_XML_VALUE)
public Map<String,Object> convertXMLtoJson(#RequestBody String strXMLData) {
Map<String,Object> objresponseMessage = null;
ObjectMapper objObjectMapper = new ObjectMapper();
Employee objEmployee = null;
try {
JSONObject obj = XML.toJSONObject(strXMLData);
ObjectMapper objectMapper = new XmlMapper();
objEmployee = objectMapper.readValue(strXMLData, Employee.class);
objEmployeeService.save(objEmployee);
} catch (Exception e) {
e.printStackTrace();
}
return objresponseMessage;
}
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.util.HashSet out of VALUE_STRING token
at [Source: (StringReader); line: 5, column: 15] (through reference chain: com.example.springboot.bean.Employee["Skills"])
<EmployeeDetail>
<FirstName>A</FirstName>
<LastName>Z</LastName>
<Age>20</Age>
<Skills>Java</Skills>
<Skills>J2EE</Skills>
<Skills>MSSQl</Skills>
<Skills>JAVA</Skills>
<TotalExperience>4</TotalExperience>
<JobDetails>
<CompanyName>1</CompanyName>
<Experience>1.5</Experience>
<Technologies>Java</Technologies>
<Technologies>WebServices</Technologies>
<Technologies>MSSQL</Technologies>
<Technologies>J2EE</Technologies>
<Location>India</Location>
</JobDetails>
<JobDetails>
<CompanyName>2</CompanyName>
<Experience>2.5</Experience>
<Technologies>Java</Technologies>
<Technologies>J2EE</Technologies>
<Technologies>MySQL</Technologies>
<Technologies>Spring</Technologies>
<Location>India</Location>
</JobDetails>
</EmployeeDetail>
Expected Json as(Output Excepted)
{
"EmployeeDetail": {
"FirstName": "A",
"LastName": "Z",
"Age": "20",
"Skills": [
"Java",
"J2EE",
"MSSQl",
"JAVA"
],
"TotalExperience": "4",
"JobDetails": [
{
"CompanyName": "1",
"Experience": "1.5",
"Technologies": [
"Java",
"WebServices",
"MSSQL",
"J2EE"
],
"Location": "India"
},
{
"CompanyName": "2",
"Experience": "2.5",
"Technologies": [
"Java",
"J2EE",
"MySQL",
"Spring"
],
"Location": "India"
}
]
}
}
Can Anyone help me to understand using Jackson library
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
#Document
#JacksonXmlRootElement(localName="EmployeeDetail")
public class Employee implements Serializable {
#Id
private String userId;
#JacksonXmlProperty(localName="FirstName")
#JsonProperty("FirstName")
private String firstName;
#JacksonXmlProperty(localName="LastName")
#JsonProperty("LastName")
private String lastName;
#JacksonXmlProperty(localName="Age")
#JsonProperty("Age")
private Integer age;
#JacksonXmlElementWrapper(localName="Skills")
#JsonProperty("Skills")
private Set<String> skills;
#JacksonXmlProperty(localName="JobDetails")
#JsonProperty("JobDetails")
private List<JobDetails> jobDetails;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public List<JobDetails> getJobDetails() {
return jobDetails;
}
public void setJobDetails(List<JobDetails> jobDetails) {
this.jobDetails = jobDetails;
}
public Set<String> getSkills() {
return skills;
}
public void setSkills(Set<String> skills) {
this.skills = skills;
}
}
import java.util.Set;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
#JacksonXmlRootElement(localName="JobDetails")
public class JobDetails {
JobDetails(String str) {
}
#JacksonXmlProperty(localName="CompanyName")
#JsonProperty("CompanyName")
private String companyName;
#JacksonXmlProperty(localName="Experience")
#JsonProperty("Experience")
private Integer experience;
#JacksonXmlProperty(localName="Location")
#JsonProperty("Location")
private String location;
#JacksonXmlElementWrapper(localName="Technologies")
#JsonProperty("Technologies")
private Set<String> technologies;
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public Integer getExperience() {
return experience;
}
public void setExperience(Integer experience) {
this.experience = experience;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public Set<String> getTechnologies() {
return technologies;
}
public void setTechnologies(Set<String> technologies) {
this.technologies = technologies;
}
}

Change your xml input data , whatever inputs are as a collection group them in tag.and modify localName in annotation " #JacksonXmlElementWrapper" in java file. Here is what is did.
<EmployeeDetail>
<FirstName>A</FirstName>
<LastName>Z</LastName>
<Age>20</Age>
<skillset>
<Skills>Java</Skills>
<Skills>J2EE</Skills>
<Skills>MSSQl</Skills>
<Skills>JAVA</Skills>
</skillset>
<TotalExperience>4</TotalExperience>
<jobs>
<JobDetails>
<CompanyName>1</CompanyName>
<Experience>1.5</Experience>
<technologyList>
<Technologies>Java</Technologies>
<Technologies>WebServices</Technologies>
<Technologies>MSSQL</Technologies>
<Technologies>J2EE</Technologies>
</technologyList>
<Location>India</Location>
</JobDetails>
<JobDetails>
<CompanyName>2</CompanyName>
<Experience>2.5</Experience>
<technologyList>
<Technologies>Java</Technologies>
<Technologies>J2EE</Technologies>
<Technologies>MySQL</Technologies>
<Technologies>Spring</Technologies>
</technologyList>
<Location>India</Location>
</JobDetails>
</jobs>
</EmployeeDetail>
Now modify your Employee.java class to following
import java.util.List;
import java.util.Set;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
#Document
#JacksonXmlRootElement(localName="EmployeeDetail")
public class Employee implements Serializable {
#Id
private String userId;
#JacksonXmlProperty(localName="FirstName")
#JsonProperty("FirstName")
private String firstName;
#JacksonXmlProperty(localName="LastName")
#JsonProperty("LastName")
private String lastName;
#JacksonXmlProperty(localName="Age")
#JsonProperty("Age")
private Integer age;
#JacksonXmlElementWrapper(localName="skillset")
#JsonProperty("Skills")
private Set<String> skills;
#JacksonXmlElementWrapper(localName="jobs")
#JsonProperty("JobDetails")
private List<JobDetails> jobDetails;
#JacksonXmlProperty(localName="TotalExperience")
#JsonProperty("totalExperience")
private Integer totalExperience;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public List<JobDetails> getJobDetails() {
return jobDetails;
}
public void setJobDetails(List<JobDetails> jobDetails) {
this.jobDetails = jobDetails;
}
public Set<String> getSkills() {
return skills;
}
public void setSkills(Set<String> skills) {
this.skills = skills;
}
public Integer getTotalExperience() {
return totalExperience;
}
public void setTotalExperience(Integer totalExperience) {
this.totalExperience = totalExperience;
}
}
your Jobdetail.java to
import java.util.Set;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
#JacksonXmlRootElement(localName="JobDetails")
public class JobDetails {
public JobDetails() {
// TODO Auto-generated constructor stub
}
JobDetails(String str) {
}
#JacksonXmlProperty(localName="CompanyName")
#JsonProperty("CompanyName")
private String companyName;
#JacksonXmlProperty(localName="Experience")
#JsonProperty("Experience")
private Float experience;
#JacksonXmlProperty(localName="Location")
#JsonProperty("Location")
private String location;
#JacksonXmlElementWrapper(localName="technologyList")
#JsonProperty("Technologies")
private Set<String> technologies;
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public FloatgetExperience() {
return experience;
}
public void setExperience(Floatexperience) {
this.experience = experience;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public Set<String> getTechnologies() {
return technologies;
}
public void setTechnologies(Set<String> technologies) {
this.technologies = technologies;
}
}
And use below method to convert your xml to Json;
public static String convertXMLtoJson( String inputxml) {
String json="";
try {
ObjectMapper objectMapper = new XmlMapper();
ObjectMapper jsonMapper = new ObjectMapper();
Employee emp = objectMapper.readValue(inputxml, Employee.class);
json =jsonMapper.writeValueAsString(emp);
System.out.println(jsonMapper.writeValueAsString(emp));
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
Here's what json data i'm getting
{"userId":null,"FirstName":"A","LastName":"Z","Age":20,"Skills":["JAVA","Java","J2EE","MSSQl"],"JobDetails":[{"CompanyName":"1","Experience":1.5,"Location":"India","Technologies":["Java","WebServices","J2EE","MSSQL"]},{"CompanyName":"2","Experience":2.5,"Location":"India","Technologies":["Java","MySQL","J2EE","Spring"]}],"totalExperience":4}

Could be useful know the implementation of Employee class.
Are you skills field annotated with #JsonProperty("Skills") as capitalized?
#JsonProperty("Skills")
private Set<String> skills;
Case sensitive should be matter.

Related

Return key value of a JSON request in Spring

I'm trying to create a route to perform a GET Request to /winner to show the restaurants that had the count of 3 votes in the JSON, but every time I do the GET, it returns the value of null instead of the value I would like.
I was expecting something like that:
{
"id": 1,
"restaurant": "Burger King",
"address": "Av. Ipiranga, 1600",
"website": "https://www.burgerking.com.br/",
"description": "Rede de fast-food famosa com hambúrgueres grelhados, batata frita e milk-shakes.",
"count": 3
}
Instead that, I'm just getting an empty JSON with the null value.
Here are the classes I'm using:
Restaurant.java
package com.dbserver.restaurantes.entities;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "db_restaurants")
public class Restaurant {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String restaurant;
private String address;
private String website;
private String description;
private Integer count;
#OneToMany(mappedBy = "id.restaurant")
private Set<Vote> votes = new HashSet<>();
public Restaurant() {
}
public Restaurant(Long id, String restaurant, String address, String website, String description, Integer count) {
this.id = id;
this.restaurant = restaurant;
this.address = address;
this.website = website;
this.description = description;
this.count = count;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRestaurant() {
return restaurant;
}
public void setRestaurant(String restaurant) {
this.restaurant = restaurant;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public Set<Vote> getVotes() {
return votes;
}
}
RestaurantDTO.java
package com.dbserver.restaurantes.dto;
import com.dbserver.restaurantes.entities.Restaurant;
public class RestaurantDTO {
private Long id;
private String restaurant;
private String address;
private String website;
private String description;
private Integer count;
public RestaurantDTO() {
}
public RestaurantDTO(Long id, String restaurant, String address, String website, String description, Integer count) {
this.id = id;
this.restaurant = restaurant;
this.address = address;
this.website = website;
this.description = description;
this.count = count;
}
public RestaurantDTO(Restaurant restaurantDTO) {
id = restaurantDTO.getId();
restaurant = restaurantDTO.getRestaurant();
address = restaurantDTO.getAddress();
website = restaurantDTO.getWebsite();
description = restaurantDTO.getDescription();
count = restaurantDTO.getCount();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRestaurant() {
return restaurant;
}
public void setRestaurant(String restaurant) {
this.restaurant = restaurant;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
}
RestaurantServices.java
package com.dbserver.restaurantes.services;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dbserver.restaurantes.dto.RestaurantDTO;
import com.dbserver.restaurantes.dto.VoteDTO;
import com.dbserver.restaurantes.entities.Restaurant;
import com.dbserver.restaurantes.repositories.RestaurantRepository;
#Service
public class RestaurantServices {
#Autowired
private RestaurantRepository repository;
#Transactional(readOnly = true)
public Page<RestaurantDTO> findAll(Pageable pageable) {
Page<Restaurant> result = repository.findAll(pageable);
Page<RestaurantDTO> page = result.map(x -> new RestaurantDTO(x));
return page;
}
#Transactional(readOnly = true)
public RestaurantDTO findById(Long id) {
Restaurant result = repository.findById(id).get();
RestaurantDTO dto = new RestaurantDTO(result);
return dto;
}
#Transactional(readOnly = true)
public Restaurant findWinner(Integer count) {
List<Restaurant> restaurants = new ArrayList<>();
for (Restaurant restaurant: restaurants) {
if(restaurant.getCount().equals(3)) {
return restaurant;
}
}
return null;
}
#Transactional
public Restaurant addRestaurant(Restaurant newRestaurant) {
return repository.saveAndFlush(newRestaurant);
}
}
RestaurantController.java
package com.dbserver.restaurantes.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.dbserver.restaurantes.dto.RestaurantDTO;
import com.dbserver.restaurantes.entities.Restaurant;
import com.dbserver.restaurantes.services.RestaurantServices;
#RestController
#RequestMapping(value = "/restaurants")
public class RestaurantController {
#Autowired
private RestaurantServices service;
#GetMapping
public Page<RestaurantDTO> findAll(Pageable pageable) {
return service.findAll(pageable);
}
#GetMapping(value = "/{id}")
public RestaurantDTO findById(#PathVariable Long id) {
return service.findById(id);
}
#SuppressWarnings("unchecked")
#GetMapping(value = "/winner")
public List<RestaurantDTO> findWinner(Integer count) {
return (List<RestaurantDTO>) service.findWinner(3);
};
#PostMapping
public Restaurant addRestaurant(#RequestBody Restaurant newRestaurant) {
return service.addRestaurant(newRestaurant);
}
}
you didn't access dao in the method findWinner.
restaurants instance has just created without accessing dao.
#Transactional(readOnly = true)
public Restaurant findWinner(Integer count) {
List<Restaurant> restaurants = new ArrayList<>();
for (Restaurant restaurant: restaurants) {
if(restaurant.getCount().equals(3)) {
return restaurant;
}
}
return null;
}
because in the find winner method you have initialized restaurants with an empty array list.
It should be like this.
#Transactional(readOnly = true)
public Restaurant findWinner(Integer count) {
List<Restaurant> restaurants = repository.findAll();
for (Restaurant restaurant: restaurants) {
if(restaurant.getCount().equals(3)) {
return restaurant;
}
}
return null;
}

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `response` out of START_ARRAY token

I keep getting this response when im trying to execute my retrofit call for this reseponse:
package retrofit.responses;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"id",
"version",
"createdDate",
"modifiedDate",
"rie",
"line1",
"line2",
"line3",
"line4",
"line5",
"county",
"postCode",
"country",
"primary",
"accomodationStatus",
"addressType",
"effectiveFrom",
"effectiveTo",
"secured"
})
#Generated("jsonschema2pojo")
public class ReferralResponse {
#JsonProperty("id")
private Object id;
#JsonProperty("version")
private Integer version;
#JsonProperty("createdDate")
private Object createdDate;
#JsonProperty("modifiedDate")
private Object modifiedDate;
#JsonProperty("rie")
private Boolean rie;
#JsonProperty("line1")
private String line1;
#JsonProperty("line2")
private Object line2;
#JsonProperty("line3")
private Object line3;
#JsonProperty("line4")
private String line4;
#JsonProperty("line5")
private Object line5;
#JsonProperty("county")
private Object county;
#JsonProperty("postCode")
private String postCode;
#JsonProperty("country")
private Object country;
#JsonProperty("primary")
private Boolean primary;
#JsonProperty("accomodationStatus")
private AccomodationStatus accomodationStatus;
#JsonProperty("addressType")
private Object addressType;
#JsonProperty("effectiveFrom")
private Long effectiveFrom;
#JsonProperty("effectiveTo")
private Object effectiveTo;
#JsonProperty("secured")
private Boolean secured;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("id")
public Object getId() {
return id;
}
#JsonProperty("id")
public void setId(Object id) {
this.id = id;
}
#JsonProperty("version")
public Integer getVersion() {
return version;
}
#JsonProperty("version")
public void setVersion(Integer version) {
this.version = version;
}
#JsonProperty("createdDate")
public Object getCreatedDate() {
return createdDate;
}
#JsonProperty("createdDate")
public void setCreatedDate(Object createdDate) {
this.createdDate = createdDate;
}
#JsonProperty("modifiedDate")
public Object getModifiedDate() {
return modifiedDate;
}
#JsonProperty("modifiedDate")
public void setModifiedDate(Object modifiedDate) {
this.modifiedDate = modifiedDate;
}
#JsonProperty("rie")
public Boolean getRie() {
return rie;
}
#JsonProperty("rie")
public void setRie(Boolean rie) {
this.rie = rie;
}
#JsonProperty("line1")
public String getLine1() {
return line1;
}
#JsonProperty("line1")
public void setLine1(String line1) {
this.line1 = line1;
}
#JsonProperty("line2")
public Object getLine2() {
return line2;
}
#JsonProperty("line2")
public void setLine2(Object line2) {
this.line2 = line2;
}
#JsonProperty("line3")
public Object getLine3() {
return line3;
}
#JsonProperty("line3")
public void setLine3(Object line3) {
this.line3 = line3;
}
#JsonProperty("line4")
public String getLine4() {
return line4;
}
#JsonProperty("line4")
public void setLine4(String line4) {
this.line4 = line4;
}
#JsonProperty("line5")
public Object getLine5() {
return line5;
}
#JsonProperty("line5")
public void setLine5(Object line5) {
this.line5 = line5;
}
#JsonProperty("county")
public Object getCounty() {
return county;
}
#JsonProperty("county")
public void setCounty(Object county) {
this.county = county;
}
#JsonProperty("postCode")
public String getPostCode() {
return postCode;
}
#JsonProperty("postCode")
public void setPostCode(String postCode) {
this.postCode = postCode;
}
#JsonProperty("country")
public Object getCountry() {
return country;
}
#JsonProperty("country")
public void setCountry(Object country) {
this.country = country;
}
#JsonProperty("primary")
public Boolean getPrimary() {
return primary;
}
#JsonProperty("primary")
public void setPrimary(Boolean primary) {
this.primary = primary;
}
#JsonProperty("accomodationStatus")
public AccomodationStatus getAccomodationStatus() {
return accomodationStatus;
}
#JsonProperty("accomodationStatus")
public void setAccomodationStatus(AccomodationStatus accomodationStatus) {
this.accomodationStatus = accomodationStatus;
}
#JsonProperty("addressType")
public Object getAddressType() {
return addressType;
}
#JsonProperty("addressType")
public void setAddressType(Object addressType) {
this.addressType = addressType;
}
#JsonProperty("effectiveFrom")
public Long getEffectiveFrom() {
return effectiveFrom;
}
#JsonProperty("effectiveFrom")
public void setEffectiveFrom(Long effectiveFrom) {
this.effectiveFrom = effectiveFrom;
}
#JsonProperty("effectiveTo")
public Object getEffectiveTo() {
return effectiveTo;
}
#JsonProperty("effectiveTo")
public void setEffectiveTo(Object effectiveTo) {
this.effectiveTo = effectiveTo;
}
#JsonProperty("secured")
public Boolean getSecured() {
return secured;
}
#JsonProperty("secured")
public void setSecured(Boolean secured) {
this.secured = secured;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
and im trying to getID and use that in another call. This is an object that I am trying to turn into an integer an then use that in a seperate call again.
referralResponseResponse = call1.getReferral(token).execute();
int i = (int) referralResponseResponse.body().getId();
System.out.println("Int: " + i);
I should also note the json that I'm using this data from is very large so ive just used jsonpogo to extract this information to a java file and then use the parts that apply to me, I dont imagine i have to set up a java class for every part of the retruned json
Try to add following annotation for your POJO class:
#JsonIgnoreProperties(ignoreUnknown = true)

Iterating through the results of the JSON response - Android + Retrofit + Moshi

{
"data": [
{
"id": 4,
"customer_id": 3,
"service_type_id": 1,
"full_name": "Teja Babu S",
"email": "testemail#gmail.com",
camera_types": 1,
"dvr_types": 1,
"created_at": "2020-01-04 14:18:30",
"updated_at": "2020-01-04 14:18:30",
"camera_type": {
"id": 1,
"name": "Analogue hd",
"description": null,
"status": 1,
"deleted_at": null,
"created_at": "2020-01-04 08:03:45",
"updated_at": "2020-01-04 08:54:23"
},
"dvr_type": {
"id": 1,
"name": "XVR - nvr",
"description": "desc",
"status": 1,
"deleted_at": null,
"created_at": "2020-01-04 08:28:04",
"updated_at": "2020-01-04 08:57:17"
}
}
]
}
I am using the http://www.jsonschema2pojo.org/ for converion. I am not pasting the result to keep the question simple.
package - package
com.tesmachino.saycure.entities.OrderHistory.OrderDetail;
ClassName - OrderDetailsResponse
Target language: Java
Source type: JSON
Annotation style: Moshi
I would like to access the Name from Both camera_type and dvr_type
I am using Moshi + retrofit
OrderDetail
package com.tesmachino.saycure;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.tesmachino.saycure.Auth.TokenManager;
import com.tesmachino.saycure.entities.OrderHistory.OrderDetail.OrderDetailsResponse;
import com.tesmachino.saycure.entities.OrderHistory.OrderHistoryResponse;
import com.tesmachino.saycure.entities.UserDetails.UserDetailsGetResponse;
import com.tesmachino.saycure.network.ApiService;
import com.tesmachino.saycure.network.RetrofitBuilder;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class OrderDetail extends AppCompatActivity {
ApiService service;
TokenManager tokenManager;
Call<OrderDetailsResponse> call;
private static final String TAG = "OrderDetail";
#BindView(R.id.orderdetails_id)
TextView orderId;
#BindView(R.id.orderdetails_client_name)
TextView orderDetailsClientName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_detail);
ButterKnife.bind(this);
tokenManager = TokenManager.getInstance(getSharedPreferences("prefs", MODE_PRIVATE));
service = RetrofitBuilder.createServiceWithAuth(ApiService.class, tokenManager);
}
#Override
protected void onResume() {
//Get the Data from the Intent
if (getIntent().hasExtra("order_id")) {
int order_id = getIntent().getIntExtra("order_id", 1);
Log.d(TAG, "IntentWorking" + order_id);
call = service.orderDetails(order_id);
call.enqueue(new Callback<OrderDetailsResponse>() {
#Override
public void onResponse(Call<OrderDetailsResponse> call, Response<OrderDetailsResponse> response) {
OrderDetailsResponse orderDetails = response.body();
if (orderDetails != null){
}
Log.w(TAG, "onResponse123: " + orderDetails.getData().get(0).getId());
Toast.makeText(OrderDetail.this, "" + response.body().toString(), Toast.LENGTH_SHORT).show();
orderId.setText(String.valueOf(orderDetails.getData().get(0).getId()));
orderDetailsClientName.setText(orderDetails.getData().get(0).getFullName());
Log.w(TAG, "onResponse45321: "+ orderDetails.getData().get(0).getCameraType());
}
#Override
public void onFailure(Call<OrderDetailsResponse> call, Throwable t) {
Log.w(TAG, "onFailure: " + t.getMessage());
Toast.makeText(OrderDetail.this, "Failure" + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(this, "There seems to be an error while fetching the Order Id. Please Try Again", Toast.LENGTH_SHORT).show();
}
super.onResume();
}
}
OrderDetailsResponse
package com.tesmachino.saycure.entities.OrderHistory.OrderDetail;
import com.squareup.moshi.Json;
import org.apache.commons.lang3.builder.ToStringBuilder;
import java.util.List;
public class OrderDetailsResponse {
#Json(name = "data")
private List<OrderDetailsGet> data = null;
public List<OrderDetailsGet> getData() {
return data;
}
public void setData(List<OrderDetailsGet> data) {
this.data = data;
}
#Override
public String toString() {
return new ToStringBuilder(this).append("data", data).toString();
}
}
OrderDetailsGet
package com.tesmachino.saycure.entities.OrderHistory.OrderDetail;
import com.squareup.moshi.Json;
import org.apache.commons.lang3.builder.ToStringBuilder;
public class OrderDetailsGet {
#Json(name = "id")
private Integer id;
#Json(name = "customer_id")
private Integer customerId;
#Json(name = "service_type_id")
private Integer serviceTypeId;
#Json(name = "full_name")
private String fullName;
#Json(name = "email")
private String email;
#Json(name = "address_line_1")
private String addressLine1;
#Json(name = "address_line_2")
private String addressLine2;
#Json(name = "phone_no")
private String phoneNo;
#Json(name = "alternate_phone_no")
private Object alternatePhoneNo;
#Json(name = "land_mark")
private Object landMark;
#Json(name = "area")
private Object area;
#Json(name = "district")
private String district;
#Json(name = "city")
private String city;
#Json(name = "state")
private String state;
#Json(name = "pincode")
private Integer pincode;
#Json(name = "type_of_property")
private Integer typeOfProperty;
#Json(name = "camera_types")
private Integer cameraTypes;
#Json(name = "no_of_cameras")
private Integer noOfCameras;
#Json(name = "dvr_types")
private Integer dvrTypes;
#Json(name = "dvr_channel")
private Integer dvrChannel;
#Json(name = "notes")
private Object notes;
#Json(name = "deleted_at")
private Object deletedAt;
#Json(name = "created_at")
private String createdAt;
#Json(name = "updated_at")
private String updatedAt;
#Json(name = "camera_type")
private CameraType cameraType;
#Json(name = "dvr_type")
private DvrType dvrType;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCustomerId() {
return customerId;
}
public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}
public Integer getServiceTypeId() {
return serviceTypeId;
}
public void setServiceTypeId(Integer serviceTypeId) {
this.serviceTypeId = serviceTypeId;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public Object getAlternatePhoneNo() {
return alternatePhoneNo;
}
public void setAlternatePhoneNo(Object alternatePhoneNo) {
this.alternatePhoneNo = alternatePhoneNo;
}
public Object getLandMark() {
return landMark;
}
public void setLandMark(Object landMark) {
this.landMark = landMark;
}
public Object getArea() {
return area;
}
public void setArea(Object area) {
this.area = area;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Integer getPincode() {
return pincode;
}
public void setPincode(Integer pincode) {
this.pincode = pincode;
}
public Integer getTypeOfProperty() {
return typeOfProperty;
}
public void setTypeOfProperty(Integer typeOfProperty) {
this.typeOfProperty = typeOfProperty;
}
public Integer getCameraTypes() {
return cameraTypes;
}
public void setCameraTypes(Integer cameraTypes) {
this.cameraTypes = cameraTypes;
}
public Integer getNoOfCameras() {
return noOfCameras;
}
public void setNoOfCameras(Integer noOfCameras) {
this.noOfCameras = noOfCameras;
}
public Integer getDvrTypes() {
return dvrTypes;
}
public void setDvrTypes(Integer dvrTypes) {
this.dvrTypes = dvrTypes;
}
public Integer getDvrChannel() {
return dvrChannel;
}
public void setDvrChannel(Integer dvrChannel) {
this.dvrChannel = dvrChannel;
}
public Object getNotes() {
return notes;
}
public void setNotes(Object notes) {
this.notes = notes;
}
public Object getDeletedAt() {
return deletedAt;
}
public void setDeletedAt(Object deletedAt) {
this.deletedAt = deletedAt;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
public CameraType getCameraType() {
return cameraType;
}
public void setCameraType(CameraType cameraType) {
this.cameraType = cameraType;
}
public DvrType getDvrType() {
return dvrType;
}
public void setDvrType(DvrType dvrType) {
this.dvrType = dvrType;
}
#Override
public String toString() {
return new ToStringBuilder(this).append("id", id).append("customerId", customerId).append("serviceTypeId", serviceTypeId).append("fullName", fullName).append("email", email).append("addressLine1", addressLine1).append("addressLine2", addressLine2).append("phoneNo", phoneNo).append("alternatePhoneNo", alternatePhoneNo).append("landMark", landMark).append("area", area).append("district", district).append("city", city).append("state", state).append("pincode", pincode).append("typeOfProperty", typeOfProperty).append("cameraTypes", cameraTypes).append("noOfCameras", noOfCameras).append("dvrTypes", dvrTypes).append("dvrChannel", dvrChannel).append("notes", notes).append("deletedAt", deletedAt).append("createdAt", createdAt).append("updatedAt", updatedAt).append("cameraType", cameraType).append("dvrType", dvrType).toString();
}
}
If you are just trying to the the name from camera_type and dvr_type, you can do:
//This assumes that you have a getCameraType & getDvrTypes method in your OrderDetailsGet class
String camera_name = orderDetails.getData().get(0).getCameraType().getName()
String dvr_name = orderDetails.getData().get(0).getDvrTypes().getName()

How to add array list to rest API request using Rest Assured?

I'm using rest assured for Rest api testing with the help of POJO classes like getter and setter methods to set the values but i'm stuck with array list in between rest request,please any one provide proper code to get exact below request to post using rest assured.
Request:
{
"firstName":"SuryaNAMASKARAM",
"lastName":"mangalam",
"mobileNo" :4954758490,
"emailId" :"surya.mangalam#futureretail.in",
"houseNoStreet":"123456",
"buildingName":"",
"landmark":"Nirmala jathara",
"paymentDetail" :
[{"paymentType":"CASH","No":"3519000012","Date":"16-06-2018","amount":"100.00"}]
}
CustomerCreate Class:
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("firstName")
#Expose
private String firstName;
#SerializedName("lastName")
#Expose
private String lastName;
#SerializedName("mobileNo")
#Expose
private Integer mobileNo;
#SerializedName("emailId")
#Expose
private String emailId;
#SerializedName("houseNoStreet")
#Expose
private String houseNoStreet;
#SerializedName("buildingName")
#Expose
private String buildingName;
#SerializedName("landmark")
#Expose
private String landmark;
#SerializedName("paymentDetail")
#Expose
private List<PaymentDetail> paymentDetail = null;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getMobileNo() {
return mobileNo;
}
public void setMobileNo(Integer mobileNo) {
this.mobileNo = mobileNo;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getHouseNoStreet() {
return houseNoStreet;
}
public void setHouseNoStreet(String houseNoStreet) {
this.houseNoStreet = houseNoStreet;
}
public String getBuildingName() {
return buildingName;
}
public void setBuildingName(String buildingName) {
this.buildingName = buildingName;
}
public String getLandmark() {
return landmark;
}
public void setLandmark(String landmark) {
this.landmark = landmark;
}
public List<PaymentDetail> getPaymentDetail() {
return paymentDetail;
}
public void setPaymentDetail(List<PaymentDetail> paymentDetail) {
this.paymentDetail = paymentDetail;
}
}
PaymentDetails:
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class PaymentDetail {
#SerializedName("paymentType")
#Expose
private String paymentType;
#SerializedName("No")
#Expose
private String no;
#SerializedName("Date")
#Expose
private String date;
#SerializedName("amount")
#Expose
private String amount;
public String getPaymentType() {
return paymentType;
}
public void setPaymentType(String paymentType) {
this.paymentType = paymentType;
}
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}
Test Class:
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.test.requestpojo.Example;
import com.test.requestpojo.PaymentDetail;
public class TestAPI {
public void setTestData() throws JSONException {
Example example = new Example();
example.setFirstName("Rajesh");
example.setLastName("Kuchana");
example.setMobileNo("3434343434");
example.setEmailId("rajesh.kuchana#futureretail.in");
example.setDateOfBirth("10-10-2018");
example.setGender(1);
example.setHouseNoStreet("Test");
example.setBuildingName("Test");
example.setLandmark("Test");
List<PaymentDetail> data = new ArrayList<PaymentDetail>();
PaymentDetail paymentDetail = new PaymentDetail();
paymentDetail.setAmount("999.00");
data.add(paymentDetail);
JSONObject jsonObject = new JSONObject(example);
JSONArray jsonArray = new JSONArray(data);
jsonArray.put(data);
System.out.println(jsonArray.put(data));
}
In your test class, what you must do is separate the test data creation to a different class and pass that as data provider to your test method. This is from design point of view.
Coming to your problem:
You are already using gson, why are you constructing a JSONObject. Instead do something like below;
Gson gson = new Gson();
String _my_obj = gson.toJson(example);
Hope this is what you are looking for.

jaxb returning null vaue after unmarshal

I am trying to Unmarshall a xml and it is returning null value
XML:
<letterOutHeader>
<lettertype>
MN13
</lettertype>
<letterReqid>
9294678
</letterReqid>
<language>
en
</language>
<attentionTo></attentionTo>
<addressLine1></addressLine1>
<addressLine2></addressLine2>
<city>Case City</city>
<state>NY</state>
<zipCode>59559</zipCode>
<dateOfLetter>12/28/2016</dateOfLetter>
<respondByDate/>
<externalNum>Ac0287356894754</externalNum>
<letterOutFlexField>
<name>fieldOne </name>
<value>valueOne</value>
</letterOutFlexField>
<letterOutFlexField>
<name>fieldTwo</name>
<value>valueTwo</value>
</letterOutFlexField>
<letterOutFlexField>
<name>fieldThree</name>
<value>valueThree</value>
</letterOutFlexField>
<letterOutFlexField>
<name>fieldFour</name>
<value>valueFour</value>
</letterOutFlexField>
</letterOutHeader>
Bean:
package jaxb.Bean;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class LetterOutHeader {
String lettertype;
String letterReqid;
String language;
String attentionTo;
String addressLine1;
String addressLine2;
String city;
String state;
String zipCode;
String dateOfLetter;
String respondByDate;
String externalNum;
List<LetterOutFlexFieldBean> flexFields;
#XmlAttribute
public String getLettertype() {
return lettertype;
}
public void setLettertype(String lettertype) {
this.lettertype = lettertype;
}
#XmlAttribute
public String getLetterReqid() {
return letterReqid;
}
public void setLetterReqid(String letterReqid) {
this.letterReqid = letterReqid;
}
#XmlAttribute
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
#XmlAttribute
public String getAttentionTo() {
return attentionTo;
}
public void setAttentionTo(String attentionTo) {
this.attentionTo = attentionTo;
}
#XmlAttribute
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
#XmlAttribute
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
#XmlAttribute
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
#XmlAttribute
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
#XmlAttribute
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
#XmlAttribute
public String getDateOfLetter() {
return dateOfLetter;
}
public void setDateOfLetter(String dateOfLetter) {
this.dateOfLetter = dateOfLetter;
}
#XmlAttribute
public String getRespondByDate() {
return respondByDate;
}
public void setRespondByDate(String respondByDate) {
this.respondByDate = respondByDate;
}
#XmlAttribute
public String getExternalNum() {
return externalNum;
}
public void setExternalNum(String externalNum) {
this.externalNum = externalNum;
}
#XmlElement
public List<LetterOutFlexFieldBean> getFlexFields() {
return flexFields;
}
public void setFlexFields(List<LetterOutFlexFieldBean> flexFields) {
this.flexFields = flexFields;
}
}
UnMarshaling :
package jaxb.client;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import jaxb.Bean.LetterOutBean;
import jaxb.Bean.LetterOutHeader;
public class XmlToObject {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
File file = new File("C:/Users/sindhu/Desktop/Kranthi/jaxB/baseXML.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(LetterOutHeader.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
LetterOutHeader que= (LetterOutHeader) jaxbUnmarshaller.unmarshal(file);
System.out.println(que.getCity());
/* System.out.println("Answers:");
List<Answer> list=que.getAnswers();
for(Answer ans:list)
System.out.println(ans.getId()+" "+ans.getAnswername()+" "+ans.getPostedby());
*/
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
I have looked into the below posts in order to avoid duplicate question
JAXB unmarshal returning null values
JAXB unmarshalling returning Null
There are many mismatch between your provided XML and JAXB class.
Firstly, there are no attributes in your sample XML, but the JAXB contains #XmlAttribute.
Secondly, it is better to declare the #XmlAccessorType explicitly or otherwise it looks for only public fields and methods.
LetterOutHeader.java
package int1.d3;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name="letterOutHeader")
#XmlAccessorType(XmlAccessType.FIELD)
public class LetterOutHeader {
String lettertype;
String letterReqid;
String language;
String attentionTo;
String addressLine1;
String addressLine2;
String city;
String state;
String zipCode;
String dateOfLetter;
String respondByDate;
String externalNum;
#XmlElement(name="letterOutFlexField")
List<LetterOutFlexFieldBean> flexField;
public String getLettertype() {
return lettertype;
}
public void setLettertype(String lettertype) {
this.lettertype = lettertype;
}
public String getLetterReqid() {
return letterReqid;
}
public void setLetterReqid(String letterReqid) {
this.letterReqid = letterReqid;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getAttentionTo() {
return attentionTo;
}
public void setAttentionTo(String attentionTo) {
this.attentionTo = attentionTo;
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getDateOfLetter() {
return dateOfLetter;
}
public void setDateOfLetter(String dateOfLetter) {
this.dateOfLetter = dateOfLetter;
}
public String getRespondByDate() {
return respondByDate;
}
public void setRespondByDate(String respondByDate) {
this.respondByDate = respondByDate;
}
public String getExternalNum() {
return externalNum;
}
public void setExternalNum(String externalNum) {
this.externalNum = externalNum;
}
public List<LetterOutFlexFieldBean> getFlexFields() {
if(flexField == null) {
flexField = new ArrayList<LetterOutFlexFieldBean>();
}
return this.flexField;
}
}

Categories

Resources