Null pointer when trying to access POJO attribute - java

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());
}
}

Related

Spring Boot - Hierarchical entities data is not returning from a rest API

I have an API method implemented in spring boot for Courses. It fetches the course by topic Id. The Course class is implemented as:
#Entity
public class Course {
#Id
private String id;
private String name;
private String description;
#ManyToOne
private Topic topic;
public Course() {
}
public Course(String id, String name, String description, String topicId) {
super();
this.id = id;
this.name = name;
this.description = description;
this.topic = new Topic(topicId, "", "");
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void setTopic(Topic t) {
this.topic = t;
}
}
And the API method is implemented as:
#RequestMapping(method=RequestMethod.GET, value="/topics/{topicId}/courses")
public RestMessage getAllCourses(#PathVariable String topicId) {
try {
List<Course> course = courseService.getAllCourses(topicId);
message = new RestMessage(course,StatusCodeEnum.OK);
return message;
} catch (Exception e) {
message = new RestMessage(e.getMessage(),StatusCodeEnum.INTERNAL_SERVER_ERROR);
message.setException(e);
return message;
}
}
The method implementation is simple, it tries to get all the courses based on the topic id and return it as a RestMessage Object. I'm using postman for the testing and in the response I am getting the list of Course but the Topic entity data is discarded.
The api response is as:
{
"data": [
{
"id": "java-streams",
"name": "Java Streams",
"description": "Java Stream learning"
}
],
"httpStatus": "OK",
"statusCode": 200,
"exception": null
}
And the RestMessage Class is defined as:
public class RestMessage {
private Object data;
private StatusCodeEnum httpStatus;
private int statusCode;
private Exception ex;
public RestMessage() {
}
public RestMessage(Object d, StatusCodeEnum c) {
data = d;
httpStatus = c;
statusCode = c.val();
}
public void setData(Object d) {
data =d;
}
public void setHttpStatus(StatusCodeEnum c) {
httpStatus = c;
}
public void setStatusCode(int c) {
statusCode = c;
}
public void setException(Exception e) {
ex = e;
}
public void setStatusCode(StatusCodeEnum c) {
httpStatus = c;
}
public Object getData() {
return data;
}
public StatusCodeEnum getHttpStatus() {
return httpStatus;
}
public Exception getException() {
return ex;
}
public int getStatusCode() {
return statusCode;
}
}
However, I have tried to debug the API endpoint and before returning the RestMessage object I have data in the required shape but after getting the json response the Topic object is truncated for all the courses.
The debug data image is attached:
I wonder what I am doing wrong in this case?
The field topic from Course doesn't have a getter, that's why is ignored by JSON serializer.
You can use Lombok annotation to automatically generate getters and setters.
Just add #Dataon class definition and you will have generated getters and setters, constructor without parameters. You will have everything for what you can said that is POJO class.
Check this link: Project lombok

Getting Null object in HashMap implementation

Iam trying t get values from a HashMap but when i call him and setText the value i always get Null, let me show the code:
MyValues.class
private List<ItemsBean> items;
public List<ItemsBean> getItems() { return items;}
public void setItems(List<ItemsBean> items) { this.items = items; }
public static class ItemsBean {
private Map<String, leakBean> Gitt;
public Map<String, leakBean> getGitt() { return Gitt;}
public void setGitt(Map<String, leakBean> Gitt) { this.Gitt = Gitt;}
public static class leakBean {
private int id;
private String dev;
public int getId() {return id; }
public String getDev(){return dev;}
public void setId(int id) { this.id = id;}
public void setDev(String dev){this.dev = dev;}
}
I´m using Gson so for get the values and use it for .setText or Toast im trying to access like this:
MyValues object;
txt1.setText(String.valueOf( object.getItems().get(0).getGitt().get("id")));
Here i get null, can someone helpme with this? i just need to access to values, also the items.size(); return 1 and must return 3
here is hte JSON:
{
"id": 1001,
"name": "Super1",
"user": {
"name": "The Super 1"
},
"items": [
{
"987987M7812b163eryrt": {
"id": 1,
"dev": "seed"
},
"90812bn120893juuh": {
"id": 2,
"dev": "none"
},
"981273jn19203nj123rg": {
"id": 3,
"dev": "mine"
}
}
]}
Try with these POJOs:
MyValues.java
public class MyValues {
private int id;
private String name;
private User user;
private List<HashMap<String, ItemsBean>> items;
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;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<HashMap<String, ItemsBean>> getItems() {
return items;
}
public void setItems(List<HashMap<String, ItemsBean>> items) {
this.items = items;
}
}
User.java
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
ItemsBean.java
public class ItemsBean {
private int id;
private String dev;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDev() {
return dev;
}
public void setDev(String dev) {
this.dev = dev;
}
}
You can no access the values like so:
object.getItems().get(0).get("987987M7812b163eryrt").getId();

How to Parse below XML using 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 :)

Spring not converting JSON Array to List of user defined objects

So I have a input Json data-
[
{
"Id": "30B05CEC6808F81C7A8B",
"eventType" :"TestEventType"
}
]
And a wrapper class-
public class CancelSeatEventDtoWrapper {
List<CancelSeatEventDto> cancelSeatDtoList;
public List<CancelSeatEventDto> getCancelSeatDtoList() {
return cancelSeatDtoList;
}
public void setCancelSeatDtoList(List<CancelSeatEventDto> cancelSeatDtoList) {
this.cancelSeatDtoList = cancelSeatDtoList;
}
}
And a POJO
public class CancelSeatEventDto {
private String eventType, Id;
public String getEventType() {
return eventType;
}
public void setEventType(String eventType) {
this.eventType = eventType;
}
public String getId() {
return Id;
}
public void setId(String Id) {
this.Id = Id;
}
}
And in a Spring controller one of the method has -
#RequestMapping(value = "/teams/id.do", method = RequestMethod.DELETE)
#ResponseBody
public String deleteId(#RequestBody CancelSeatEventDtoWrapper jsonValue)
After running it i get a 400 Bad Request error.
Any idea whats wrong?

I parsed nested json data with gson but return null

I'm a new android developer.. So I have a problem this.. I'm parsing nested json data with gson but return null varaible. Please help me.!
My json Data is:
{"result":"success","data":{"Items":[{"id":"5b7c8950-692a-11e6-a3c9-03b4285ed321","accountName":"5b7c8950-692a-11e6-a3c9-03b4285ed321#finanskutusu.com","userId":"111903139847063022019"}],"Count":1,"ScannedCount":12}}
AccountModel.java :
public class AccountModel {
private String result;
public Data data;
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}}
Data.java :
public class Data {
public Items[] Items;
private String Count;
private String ScannedCount;
public Items[] getItems() {
return Items;
}
public void setItems(Items[] Items) {
this.Items = Items;
}
public String getCount() {
return Count;
}
public void setCount(String Count) {
this.Count = Count;
}
public String getScannedCount() {
return ScannedCount;
}
public void setScannedCount(String ScannedCount) {
this.ScannedCount = ScannedCount;
}}
Items.java :
public class Items {
private String id;
private String accountName;
private String userId;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}}
Thanks..
I have parsed the data successfully using the model classes provided (no changes). Here is the parser program,
Gson gson = new GsonBuilder().create();
AccountModel am = gson.fromJson("{\"result\":\"success\",\"data\": {\"Items\":[{\"id\":\"5b7c8950-692a-11e6-a3c9- 03b4285ed321\",\"accountName\":\"5b7c8950-692a-11e6-a3c9-03b4285ed321#finanskutusu.com\",\"userId\":\"111903139847063022019\"}],\"Count\":1,\"ScannedCount\":12}}", AccountModel.class);
System.out.println(am.getResult());
System.out.println(am.getData().getCount());
Items i[] = am.getData().getItems();
System.out.println(i[0].getAccountName());
Output
success
1
5b7c8950-692a-11e6-a3c9-03b4285ed321#finanskutusu.com

Categories