How to Parse below XML using java? - java

Iam trying to get Status and message tag info using java 1.7
Please any guide me ,
Thanks in advance
<API version="0.0">
<response>
<operation name="ADD">
<result>
<statuscode>200</statuscode>
<status>Success</status>
<message> successfully</message>
</result>
<Details type="ADD"/>
</operation>
</response>
</API>

This is not a JSON response that you are getting, it's an XML response,
you just need to convert the XML response to POJO class and use the POJO class instead.
Here is how the POJO class will look like
public class MyPojo{
private API API;
public API getAPI() {
return API;
}
public void setAPI(API API) {
this.API = API;
}
}
now MyPojo will contain another class named API
public class API {
private Response response;
private String version;
public Response getResponse() {
return response;
}
public void setResponse(Response response) {
this.response = response;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}
now the API class contains another class called Response
public class Response {
private Operation operation;
public Operation getOperation() {
return operation;
}
public void setOperation(Operation operation) {
this.operation = operation;
}
}
Now the Response class is containing another class called Operation
public class Operation {
private Result result;
private Details Details;
private String name;
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
public Details getDetails() {
return Details;
}
public void setDetails(Details Details) {
this.Details = Details;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Now you guessed it the Operation class is containing two classes Details and Result
Here is the Result class that is containing the status and message you want to access
public class Result {
private String message;
private String status;
private int statuscode;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public int getStatuscode() {
return statuscode;
}
public void setStatuscode(int statuscode) {
this.statuscode = statuscode;
}
}
Here is the Details class
public class Details {
private String type;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
finally, you can access the status and message by creating an object from MyPojo class like this:
String message = myPojo.getAPI().getResponse().getOperation().getResult().getMessage();
String status = myPojo.getAPI().getResponse().getOperation().getResult().getStatus();
you can use this online converter to convert XML/JSON to POJO.
I hope my answer was helpful :)

Related

Retrofit multiple JSON Response

Why can't I assign a value to status during JSON response. How to read the integer status? Thanks for help !
Model:
public class JsonResponse {
public String code;
public Integer status;
public String getCode() { return code; }
public Integer getStatus() { return status; }
}
Response JSON:
{
"code": "jwt_auth_valid_token",
"data": {
"status": 200
}
}
Result: getStatus(): Null
Because status is inside object called data so you should create data class that will save the status for example
public class Data {
public int status;
}
public class JsonResponse {
public String code;
public Data data;
public String getCode() { return code; }
public Integer getStatus() { return data.status;}
}
as answered Marwa Eltayeb but we can modify the answer more with :
public class JsonResponse {
#SerializedName("code")
public String code;
#SerializedName("data")
public Data data;
public String getCode() {
return code;
}
public Data getData() {
return data;
}
public class Data {
#SerializedName("status")
public int status;
public int getStatus() {
return status;
}
}
}

#ResponseBody, don't respect the constructors of an object

I have a #restController type controller, when I access a resource for a request I get a json as a response, the problem is that all attributes appear to me and it does not respect the constructors I have generated.
However, all the attributes of the class always appear to me:
{
"code":0,
"message":"ERROR",
"details":null
}
And I would like the answer to be like this:
{
"code":0,
"message":"ERROR"
}
I appreciate your help
#RestController
#RequestMapping("/api")
public class WsController implements WsInterface{
#Override
#PostMapping("/add")
public Response add(#RequestBody Person person) {
Response r= =null;
if(person.getName().equals("A")){
r= new Response(1,"OK","Details of person");
}else{
r= new Response (0,"ERROR");
}
return r;
}
}
public class Response{
private int code;
private String message;
private String details;
public Response() {
}
public Response(int code, String message, String details) {
this.code = code;
this.message = message;
this.details = details;
}
public Response(int code, String message) {
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
If you want to use same object in both cases with null details and without. You can try to configure json serialization accordingly.Spring by default use Jackson and you can configure object mapper directly or use annotation #JsonInclude(Include.NOT_NULL) on model class to include only not null values.

Null pointer when trying to access POJO attribute

I am using Retrofit 2 to consume an JSON API, I have the following JSON structure
{
"data": {
"id": 1,
"name": "Josh"
}
}
My User POJO looks like:
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And my User interface
#GET("/api/v1/me")
Call<User> me();
But I when I try and do response.body().getName() I get a null pointer exception.
The code which is making the request
UserService userService = ServiceGenerator.createService(UserService.class)
Call<User> call = userService.me();
call.enqueue(new Callback<User>() {
#Override
public void onResponse(Response<User> response, Retrofit retrofit) {
if(response.isSuccess()) {
Log.i("user", response.body().getName().toString());
}
}
#Override
public void onFailure(Throwable t) {
Log.i("hello", t.getMessage());
}
});
You should create the POJO classes as follows:
POJO for json response:
public class User {
private Data data;
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
}
POJO for internal Data:
public class Data {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Than use response.body().getData().getName() to access name in response.
public class Data {
private User data;
public String getData() {
return data;
}
public void setName(User data) {
this.data = data;
}
}
Access it like this
public void onResponse(Response<Data> response, Retrofit retrofit) {
if(response.isSuccess()) {
Log.i("user", response.body().getData().getName().toString());
}
}

want to deserialize json string into java object with arraylist

java object: MyObject has a list of AnotherObject1 and AnotherObject1 also have a list of AnotherObject2
class MyObject{
private String status;
private String message;
private List<AnotherObject1> data;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<AnotherObject1> getData() {
return data;
}
public void setData(List<AnotherObject1> data) {
this.data = data;
}
}
Class AnotherObject1{
private Integer group_id;
private List<AnotherObject2> anotherList;
public Integer getGroup_id() {
return group_id;
}
public void setGroup_id(Integer group_id) {
this.group_id = group_id;
}
public List<AnotherObject2> getAnotherList() {
return smsList;
}
public void setAnotherList(List<AnotherObject2> anotherList) {
this.anotherList = anotherList;
}
}
class AnotherObject2{
private String customid;
private String customid1 ;
private Long mobile;
private String status;
private String country;
public String getCustomid() {
return customid;
}
public void setCustomid(String customid) {
this.customid = customid;
}
public String getCustomid1() {
return customid1;
}
public void setCustomid1(String customid1) {
this.customid1 = customid1;
}
public Long getMobile() {
return mobile;
}
public void setMobile(Long mobile) {
this.mobile = mobile;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
JSON String: this is my json string by which i want to make an java object using object mapper
String response="{\"status\":\"OK\",\"data\":{\"group_id\":39545922,\"0\":{\"id\":\"39545922-1\",\"customid\":\"\",\"customid1\":\"\",\"customid2\":\"\",\"mobile\":\"910123456789\",\"status\":\"XYZ\",\"country\":\"IN\"}},\"message\":\"WE R Happy.\"}"
ObjectMapper code
//convert string to response object
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
objectMapper.readValue(responseBody, MyObject.class);
exception: here is the exception
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
at [Source: {"status":"OK","data":{"group_id":39545922,"0":{"id":"39545922-1","customid":"","customid1":"","customid2":"","mobile":"910123456789","status":"GOOD","country":"IN"}},"message":"We R happy."}; line: 1, column: 15] (through reference chain: MyObject["data"])
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:854)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:850)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.handleNonArray(CollectionDeserializer.java:292)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:227)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:217)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:25)
at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:520)
at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:95)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:256)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:125)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3702)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2714)
at abc.disp(RestClientImpl.java:210)
at abc.disp(RestClientImpl.java:105)
at Application.<init>(Application.java:42)
at Application.main(Application.java:45)
please guide me how to make it possible.
Your code itself is not compailable ...
private List<AnotherObject1> data; // Your class member is list of AnotherObject1
and below it is used as List of SMSDTO in getter and setter
public List<SMSDTO> getData() {
return data;
}
Problem is quite simple: you claim data should become Java List; and this requires that JSON input for it should be JSON Array. But what JSON instead has is a JSON Object.
So you either need to change POJO definition to expect something compatible with JSON Object (a POJO or java.util.Map); or JSON to contain an array for data.
First as Naveen Ramawat said your code is not compilable as it is.
In the class AnotherObject1 getSmsList should take AnotherObject2 and setSmsList should take AnotherObject2 also as parameter.
In the class MyObject setData and getData should use AnotherObject1 as parameters
Second your JSON string is not valid it should be sommething like that:
{"status":"OK","data":[{"group_id":39545922,"smsList":[{"customid":"39545922-1","customid1":"","mobile":913456789,"status":"XYZ","country":"XYZ"}]}]}
Here is the code that I used :
MyObject.java:
import java.util.List;
class MyObject {
private String status;
private String message;
private List<AnotherObject1> data;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<AnotherObject1> getData() {
return data;
}
public void setData(List<AnotherObject1> data) {
this.data = data;
}
}
AnotherObject1.java :
import java.util.List;
public class AnotherObject1 {
private Integer group_id;
private List<AnotherObject2> smsList;
public Integer getGroup_id() {
return group_id;
}
public void setGroup_id(Integer group_id) {
this.group_id = group_id;
}
public List<AnotherObject2> getSmsList() {
return smsList;
}
public void setSmsList(List<AnotherObject2> smsList) {
this.smsList = smsList;
}
}
AnotherObject2.java :
public class AnotherObject2 {
private String customid;
private String customid1;
private Long mobile;
private String status;
private String country;
public String getCustomid() {
return customid;
}
public void setCustomid(String customid) {
this.customid = customid;
}
public String getCustomid1() {
return customid1;
}
public void setCustomid1(String customid1) {
this.customid1 = customid1;
}
public Long getMobile() {
return mobile;
}
public void setMobile(Long mobile) {
this.mobile = mobile;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
To get the JSON string :
import org.json.JSONObject;
import org.json.XML;
import com.google.gson.Gson;
MyObject myObj = new MyObject();
ArrayList<AnotherObject2> smsList = new ArrayList<AnotherObject2>();
ArrayList<AnotherObject1> data = new ArrayList<AnotherObject1>();
AnotherObject1 ao1 = new AnotherObject1();
ao1.setGroup_id(39545922);
ao1.setSmsList(smsList);
AnotherObject2 sms = new AnotherObject2();
sms.setCountry("XYZ");
sms.setCustomid("39545922-1");
sms.setCustomid1("");
sms.setMobile((long) 913456789);
sms.setStatus("XYZ");
smsList.add(sms);
ao1.setSmsList(smsList);
data.add(ao1);
myObj.setStatus("OK");
myObj.setData(data);
// Build a JSON string to display
Gson gson = new Gson();
String jsonString = gson.toJson(myObj);
System.out.println(jsonString);
// Get an object from a JSON string
MyObject myObject2 = gson.fromJson(jsonString, MyObject.class);
// Display the new object
System.out.println(gson.toJson(myObject2));

Stop converting < to &lt, > to &gt and & to & in spring controller response

I am trying to generate a small xml. This xml should have a CDATA in it. Now the problem is I managed to generate CDATA, but the xml that is generated have < and > and &
I am using spring-mvc. I am interested in getting the right xml with CDATA in it.
Sample xml is as follow :
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Customer>
<Active>1</Active>
<AlertMessage></AlertMessage>
<Currency>GBP</Currency>
<CustomerNumber>123</CustomerNumber>
<Forename>AD</Forename>
<balancetoallow>
<balance saving="10" spend="9990" type="2">
<value>\<![CDATA[$100 off on two purchase of jeans XYZ Brand.]]\></value>
</balance>
</balancetoallow>
<Surname>CD</Surname>
</Customer>
I have also overridden one of the converter as follow.
<mvc:annotation-driven>
<mvc:message-converters>
<bean
class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter">
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
P.S I am using spring rest controller for my web service.
Here is the model class :
public class Balance{
private String value;
private String type;
private String saving;
private String spend;
public String getValue() {
return value;
}
#XmlJavaTypeAdapter(AdapterCDATA.class)
public void setValue(String value) {
this.value = value;
}
public String getType() {
return type;
}
#XmlAttribute
public void setType(String type) {
this.type = type;
}
public String getSaving() {
return saving;
}
#XmlAttribute
public void setSaving(String saving) {
this.saving = saving;
}
public String getSpend() {
return spend;
}
#XmlAttribute
public void setSpend(String spend) {
this.spend = spend;
}
}
This class is again part of another class.
public class Balancetoallows {
private List<Balance> balancetoallow ;
public List<Balance> getBalancetoallow () {
return balancetoallow;
}
#XmlElement(name="balancetoallow ")
public void setBalancetoallow (List<Balance > balancetoallow ) {
this.balancetoallow= balancetoallow;
}
}
And this is part of this class.
The parent class.
#XmlRootElement(name = "Customer")
public class Customer {
private String surname ;
private String forename;
private BalanceToAllow balanceToAllow;
private final String active="1";
private final String currency = "GBP";
private final String alertMessage="";
public String getCustomerNumber() {
return customerNumber;
}
#XmlElement(name="CustomerNumber")
public void setCustomerNumber(String customerNumber) {
this.customerNumber = customerNumber;
}
#XmlElement(name="Active")
public String getActive() {
return active;
}
#XmlElement(name="Currency")
public String getCurrency() {
return currency;
}
public String getSurname() {
return surname;
}
#XmlElement(name="Surname")
public void setSurname(String surname) {
this.surname = surname;
}
public String getForename() {
return forename;
}
#XmlElement(name="Forename")
public void setForename(String forename) {
this.forename = forename;
}
#XmlElement(name="AlertMessage")
public String getAlertMessage() {
return alertMessage;
}
public BalanceToAllow getBalanceToAllow() {
return BalanceToAllow;
}
#XmlElement(name="balanceToAllow")
public void setFuturePromotions(BalanceToAllow balanceToAllow) {
this.balanceToAllow= balanceToAllow;
}
}
Thanks for reading.

Categories