When I get List from server with spring I get in client object user like this:
{
"id": 1,
"name": "hgfhj",
"age": 120,
"createdDate": 1457211138000,
"admin": true
}
UserController.java method:
#RequestMapping(value = "/user/", method = RequestMethod.GET)
public ResponseEntity<List<User>> getList() {
List usersList = userService.getList();
ResponseEntity<List<User>> respEntity = null;
if(usersList.isEmpty()){
respEntity =new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);
return respEntity;
}
respEntity =new ResponseEntity<List<User>>(usersList, HttpStatus.OK);
return respEntity;
}
And when I use Gson I get in client object user like this:
{
"id": 1,
"name": "hgfhj",
"age": 120,
"isAdmin": true,
"createdDate": "Mar 5, 2016 10:52:18 PM"
}
UserController.java method:
#RequestMapping(value = "/user/", method = RequestMethod.GET)
public String getList() {
List usersList = userService.getList();
ResponseEntity<List<User>> respEntity = null;
respEntity =new ResponseEntity<List<User>>(usersList, HttpStatus.OK);
Gson gson = new Gson();
String json = gson.toJson(usersList);
return json;
}
In all project user property name "isAdmin", I do not understand why it's changed to "admin". How can I use spring but get in client "isAdmin" without gson?
User.java:
#Entity
public class User {
/*#Column(name="id")*/
#Id
#GeneratedValue
private int id;
#Column(name="name")
private String name;
#Column(name="age")
private int age;
#Column(name="isAdmin")
private boolean isAdmin;
#Column(name="createdDate")
#Temporal(TemporalType.TIMESTAMP)
#DateTimeFormat(pattern = "dd.MM.yyyy")
private Date createdDate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public boolean isAdmin() {
return isAdmin;
}
public Date getCreatedDate() {
return createdDate;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setIsAdmin(boolean isAdmin) {
this.isAdmin = isAdmin;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
}
please do following changes into your User class's setter method,
#JsonProperty("isAdmin") // i guess you want isAdmin into response..
public void setIsAdmin(boolean isAdmin) {
this.isAdmin = isAdmin;
}
Annotate your User objects attributes with #JsonProperty to spesify the name you want as output.
Example
public class User {
...
#SerializedName("isAdmin")
#Column(name="isAdmin")
private boolean admin;
...
}
this will return something like
{
"isAdmin" : true
}
for more information: http://www.javacreed.com/gson-annotations-example/
Updated:
For future reference #JsonProperty("name") needs to be on the getters with gson, not the attributes.
Related
I am trying to create a schema where I have 3 tables, Customer, Orders, and Products that have One to Many relationships. For example, 1 Customer can have many Orders and 1 Order can have many Products (is this possible?). I am able to add a Customer that contains a list of Orders through my post request in postman to satisfy the relationship. However, I cannot do the same for adding a list of Products to an Order. I am getting the error in OrderResource java.lang.IllegalArgumentException: Entity must not be null.. Why is my OrderResource reading a null entity when trying to post a new Order with a list of Products? How can I fix this? Thanks for any help in advance.
HTTP Get request from CustomerResource that shows an empty "products" list in "orders"
{
"id": 1,
"firstName": "Charlie",
"lastName": "Madge",
"email": "cmadge0#fc2.com",
"address": "21556 Arizona Crossing",
"password": "l7QFUwG",
"orders": [
{
"id": 1,
"tracking": "123456789",
"date": "2012-04-23T18:25:43.000+00:00",
"total": "100",
"quantity": "4",
"payment": "Paypal",
"products": []
},
{
"id": 2,
"tracking": "987654321",
"date": "2022-04-23T18:25:43.000+00:00",
"total": "90",
"quantity": "3",
"payment": "Visa",
"products": []
}
]
}
HTTP Post request I used for /assignProducts endpoint which produced the internal server error status 500
{
"orders": {
"id": "1",
"tracking": "123456789",
"date": "2012-04-23T18:25:43.511Z",
"total": "100",
"quantity": "4",
"payment": "Paypal",
"products": [
{
"title": "abc",
"price": "10",
"image": "fdfhsdfh"
}
]
}
}
Orders.java
#Entity
public class Orders implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(nullable = false, updatable = false)
private Long id;
private String tracking;
private Date date;
private String total;
private String quantity;
private String payment;
#JsonIgnore
#OneToMany(targetEntity = Products.class, cascade = CascadeType.ALL)
#JoinColumn(name = "op_fk", referencedColumnName = "id")
private List<Products> products;
public Orders() { }
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getTracking() { return tracking; }
public void setTracking(String tracking) { this.tracking = tracking; }
public Date getDate() { return date; }
public void setDate(Date date) { this.date = date; }
public String getTotal() { return total; }
public void setTotal(String total) { this.total = total; }
public String getQuantity() { return quantity; }
public void setQuantity(String quantity) { this.quantity = quantity; }
public String getPayment() { return payment; }
public void setPayment(String payment) { this.payment = payment; }
public List<Products> getProducts() { return products; }
public void setProducts(List<Products> products) { this.products = products; }
}
Products.java
#Entity
public class Products implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(nullable = false, updatable = false)
private Long id;
private String title;
private String price;
private String image;
public Products() { }
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getPrice() { return price; }
public void setPrice(String price) { this.price = price; }
public String getImage() { return image; }
public void setImage(String image) { this.image = image; }
}
OrdersResource.java
#RestController
#RequestMapping("/orders")
public class OrdersResource {
#Autowired
private final OrdersService ordersService;
public OrdersResource(OrdersService ordersService) { this.ordersService = ordersService; }
#GetMapping("/all")
public ResponseEntity<List<Orders>> getAllOrders(){
List<Orders> orders = ordersService.findAllOrders();
return new ResponseEntity<>(orders, HttpStatus.OK);
}
#GetMapping("/find/{id}")
public ResponseEntity<Orders> getOrderById(#PathVariable("id") Long id){
Orders orders = ordersService.findOrderById(id);
return new ResponseEntity<>(orders, HttpStatus.OK);
}
#PostMapping("/add")
public ResponseEntity<Orders> addOrder(#RequestBody Orders order){
Orders newOrder = ordersService.addOrder(order);
return new ResponseEntity<>(newOrder, HttpStatus.CREATED);
}
#PostMapping("/assignProducts")
public ResponseEntity<Orders> assignProduct(#RequestBody AssignProductRequest request){
Orders newOrder = ordersService.addOrder(request.getOrder());
return new ResponseEntity<>(newOrder, HttpStatus.CREATED);
}
#PostMapping("/update")
public ResponseEntity<Orders> updateOrder(#RequestBody AssignProductRequest request){
Orders updateOrder = ordersService.updateOrder(request.getOrder());
return new ResponseEntity<>(updateOrder, HttpStatus.OK);
}
#Transactional
#DeleteMapping("/delete/{id}")
public ResponseEntity<?> deleteOrder(#PathVariable("id") Long id){
ordersService.deleteOrderById(id);
return new ResponseEntity<>(HttpStatus.OK);
}
}
OrdersService.java
#Service
public class OrdersService {
private final OrdersRepo ordersRepo;
#Autowired
public OrdersService(OrdersRepo ordersRepo) { this.ordersRepo = ordersRepo; }
public Orders addOrder(Orders order){ return ordersRepo.save(order); }
public List<Orders> findAllOrders(){ return ordersRepo.findAll(); }
public Orders updateOrder(Orders order){ return ordersRepo.save(order); }
public Orders findOrderById(Long id){
return ordersRepo.findOrderById(id)
.orElseThrow(()-> new OrderNotFoundException("Order by id " + id + " was not found"));
}
public void deleteOrderById(Long id){ ordersRepo.deleteOrderById(id); }
}
AssignProductsRequest.java
#Data
#AllArgsConstructor
#NoArgsConstructor
#ToString
public class AssignProductRequest { private Orders order; }
ProductsResource.java
#RestController
#RequestMapping("/products")
public class ProductsResource {
#Autowired
private final ProductsService productsService;
public ProductsResource(ProductsService productsService) { this.productsService = productsService; }
#GetMapping("/all")
public ResponseEntity<List<Products>> getAllProducts(){
List<Products> products = productsService.findAllProducts();
return new ResponseEntity<>(products, HttpStatus.OK);
}
#GetMapping("/find/{id}")
public ResponseEntity<Products> getProductById(#PathVariable("id") Long id){
Products product = productsService.findProductById(id);
return new ResponseEntity<>(product, HttpStatus.OK);
}
#PostMapping("/add")
public ResponseEntity<Products> addProduct(#RequestBody Products product){
Products newProduct = productsService.addProduct(product);
return new ResponseEntity<>(newProduct, HttpStatus.CREATED);
}
#PostMapping("/update")
public ResponseEntity<Products> updateProduct(#RequestBody ProductsRequest request){
Products updateProduct = productsService.updateProduct(request.getProduct());
return new ResponseEntity<>(updateProduct, HttpStatus.OK);
}
#Transactional
#DeleteMapping("delete/{id}")
public ResponseEntity<?> deleteProduct(#PathVariable("id") Long id){
productsService.deleteProduct(id);
return new ResponseEntity<>(HttpStatus.OK);
}
}
ProductsService.java
#Service
public class ProductsService {
private final ProductsRepo productsRepo;
#Autowired
public ProductsService(ProductsRepo productsRepo) { this.productsRepo = productsRepo; }
public Products addProduct(Products product){ return productsRepo.save(product); }
public Products updateProduct(Products products){ return productsRepo.save(products); }
public List<Products> findAllProducts(){ return productsRepo.findAll(); }
public Products findProductById(Long id){
return productsRepo.findProductById(id)
.orElseThrow(()-> new ProductNotFoundException("Product by id " + id + " was not found"));
}
public void deleteProduct(Long id){
productsRepo.deleteProductById(id);
}
}
OrdersRepo.java
public interface OrdersRepo extends JpaRepository<Orders, Long> {
void deleteOrderById(Long id);
Optional<Orders> findOrderById(Long id);
}
ProductsRepo.java
public interface ProductsRepo extends JpaRepository<Products, Long> {
void deleteProductById(Long id);
Optional<Products> findProductById(Long id);
}
I tried using the dynamodbmapper for crud operations over the table. When I am using the save functionality from the mapper code getting executed with out any error or exceptions but when I scan the table records were not reflecting what could be the possible error I am doing in below way
try{
User user = new User();
/* added some dummy data to user object*/
static AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
static DynamoDBMapper dynamoDB = new DynamoDBMapper(client, new DynamoDBMapperConfig(DynamoDBMapperConfig.SaveBehavior.CLOBBER));
dynamoDB.save(user);
}catch(Exception e){
}
My class object
#DynamoDBTable(tableName = "users")
public class User {
private String id;
private String user_id;
private String email;
private String name;
private String mobile_no;
private Integer createdDate;
private Integer modifiedDate;
#DynamoDBHashKey(attributeName = "id")
public String getId(){
return id;
}
public void setId(String id) {
this.id = id;
}
#DynamoDBAttribute(attributeName = "user_id")
public String getUser_id() {
return user_id;
}
public void setUser_id_ref(String user_id) {
this.user_id = user_id;
}
#DynamoDBAttribute(attributeName = "email")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#DynamoDBAttribute(attributeName = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#DynamoDBAttribute(attributeName = "mobile_no")
public String getMobile_no() {
return mobile_no;
}
public void setMobile_no(String mobile_no) {
this.mobile_no = mobile_no;
}
#DynamoDBAttribute(attributeName = "created_date")
public Integer getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Integer createdDate) {
this.createdDate = createdDate;
}
#DynamoDBAttribute(attributeName = "modified_date")
public Integer getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(Integer modifiedDate) {
this.modifiedDate = modifiedDate;
}
For scanning i have used the command
aws dynamodb scan --table-name users
Result for the above command is coming as below
{
"Items": [],
"Count": 0,
"ScannedCount": 0,
"ConsumedCapacity": null
}
Table Description
aws dynamodb describe-table --table-name users
{
"Table": {
"AttributeDefinitions": [
{
"AttributeName": "id",
"AttributeType": "S"
}
],
"TableName": "users",
"KeySchema": [
{
"AttributeName": "id",
"KeyType": "HASH"
}
],
"TableStatus": "ACTIVE",
"CreationDateTime": "2022-09-29T19:33:02.692000+05:30",
"ProvisionedThroughput": {
"LastDecreaseDateTime": "2022-09-29T19:45:29.763000+05:30",
"NumberOfDecreasesToday": 0,
"ReadCapacityUnits": 1,
"WriteCapacityUnits": 1
}
}
How ever I tried creating a test class where I just have hashkey attribute and tried saving the data it got persisted
package com.moneyview.model.dynamo;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAutoGeneratedKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable;
import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType;
#DynamoDBTable(tableName = "users")
public class UserTest {
private String id;
#DynamoDBHashKey(attributeName = "id")
public String getId(){
return id;
}
public void setId(String id) {
this.id = id;
}
}
test code for inserting
public void testinsertItem(){
try{
UserTest test = new UserTest();
test.setId("8a8180967e8b5112017e8b99268702df");
dynamoDB.save(test);
}catch (Exception e){
System.out.println("Something went wrong while inserting the records to DynamoDb");
}
}
When I tried scanning the table
aws dynamodb scan --table-name users
Result:
{
"Items": [
{
"id": {
"S": "8a8180967e8b5112017e8b99268702df"
}
}
],
"Count": 1,
"ScannedCount": 1,
"ConsumedCapacity": null
}
not sure where I am doing wrong or if there is any issue in the config please help me
The code which you shared is correct, and the item should be persisted.
However, you would need to show your full class, and confirm how you are checking the item exists?
You mention it doesn't exist when your Scan? Are you scanning from your code directly after writing? Check that you have made your Scan Strongly Consistent to ensure you get the latest value.
https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Scan.html#DDB-Scan-request-ConsistentRead
If this does not resolve the issue, I will be able to help you further when you share the rest of your code.
Reviewing your updated code it seems pretty fine, I did notice some issues with the setters you defined, but i'm not certain that is your issue. The below code snippet works for me:
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.datamodeling.*;
import java.util.List;
public class UserOverflow {
public static void main(String[] args){
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
DynamoDBMapper dynamoDB = new DynamoDBMapper(client, new DynamoDBMapperConfig(DynamoDBMapperConfig.SaveBehavior.CLOBBER));
User myUser = new User();
myUser.setId("1");
try{
dynamoDB.save(myUser);
}catch(Exception e){
System.out.println(e.getMessage());
}
DynamoDBScanExpression scanExpression = new DynamoDBScanExpression()
.withConsistentRead(Boolean.TRUE);
try{
List<User> scanResult = dynamoDB.scan(User.class, scanExpression);
for (User user : scanResult) {
System.out.println(user.getId());
}
}catch (Exception e){
System.out.println(e.getMessage());
}
}
#DynamoDBTable(tableName = "users")
public static class User {
private String id;
private String user_id;
private String email;
private String name;
private String mobile_no;
private Integer createdDate;
private Integer modifiedDate;
#DynamoDBHashKey(attributeName = "id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#DynamoDBAttribute(attributeName = "user_id")
public String getUserId() {
return user_id;
}
public void setUserId(String user_id) {
this.user_id = user_id;
}
#DynamoDBAttribute(attributeName = "email")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#DynamoDBAttribute(attributeName = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#DynamoDBAttribute(attributeName = "mobile_no")
public String getMobileNo() {
return mobile_no;
}
public void setMobileNo(String mobile_no) {
this.mobile_no = mobile_no;
}
#DynamoDBAttribute(attributeName = "created_date")
public Integer getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Integer createdDate) {
this.createdDate = createdDate;
}
#DynamoDBAttribute(attributeName = "modified_date")
public Integer getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(Integer modifiedDate) {
this.modifiedDate = modifiedDate;
}
}
}
I'm not sure if your did not have log statements inside your catch block but that is one thing you should definitely add. Should that fail, I would take a look at the following:
IAM policy, do you have the correct permissions
Internet access, does where you are executing the code from have a path to the DynamoDB endpoint?
When I do a post request on Postman I receive a "200 OK" status. But doing a get request returns null JSON values
This is my user class
public class User {
private Integer id;
private String name;
private Date birthDate;
public User(Integer id, String name, Date birthDate) {
super();
this.id = id;
this.name = name;
this.birthDate = birthDate;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
#Override
public String toString() {
return String.format("User [id=%s, name=%s, birthDate=%s]", id, name, birthDate);
}
}
The UserDaoService class
#Component
public class UserDaoService {
static List<User> users = new ArrayList<>();
public static int userCount = 3;
static {
users.add(new User(1,"Eva",new Date()));
users.add(new User(2,"Mike",new Date()));
users.add(new User(3,"Dave",new Date()));
}
public List<User> findAllUsers() {
return users;
}
public User save(User user) {
if(user.getId() == null)
user.setId(++userCount);
users.add(user);
return user;
}
public User findOne(int id) {
for(User user:users )
if(user.getId() == id)
return user;
return null;
}
}
and the controller
#RestController
public class UserResource {
#Autowired
private UserDaoService service;
#GetMapping("/users")
public List<User> retrieveAllUsers(){
return service.findAllUsers();
}
#GetMapping("users/{id}")
public User retrieveUser(#PathVariable int id) {
return service.findOne(id);
}
#PostMapping("/users")
public void createUser(User user) {
User saved = service.save(user);
}
}
This is the post request I make
{
"name": "Luna",
"birthDate": "2000-08-23T23:58:45.849+00:00"
}
I didn't pass in an ID because that is covered in the backend. On making a get request the name and birthDates both have null values but the ID is set correctly.
Any ideas where I could have gone wrong?
you are missing #RequestBody in the post method param
#PostMapping("/users")
public void createUser(#RequestBody User user) {
User saved = service.save(user);
}
In Rest Assured Framework POST response is not showing ID created and Time that I am getting through POSTMAN.
#Test
public void newuser() {
service = new services();
// response = service.addProduct("444", "OIL","Natural Tea Tree", "210.0");
response = service.AddUser("Gagan", "leeee");
if (response.statusCode() == 201) {
Gson gson = new Gson();
System.out.println(response.asString());
PostUser[] userlist = gson.fromJson(response.asString(), PostUser[].class);
System.out.println(userlist[0].getCreatedAt());
System.out.println(response.statusCode());
}
}
}
Eclipse Console Output-----
[{"name":"Gagan","job":"leeee"}]
null
201
Postman Output
{
"name": "Gagan",
"job": "leee",
"id": "327",
"createdAt": "2019-02-08T07:42:50.664Z"
}
PostUser Class
package webservices.responsePOJO;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class PostUser {
#SerializedName("name")
#Expose
private String name;
#SerializedName("job")
#Expose
private String job;
#SerializedName("id")
#Expose
private String id;
#SerializedName("createdAt")
#Expose
private String createdAt;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
}
I have been fighting with Retrofit 2.3 for about 2 weeks now. The List always comes back as empty for me. It simply makes a call and gets the JSON information yet it won't process the list.
Json appears like this:
{
"users": [
{
"id": 2,
"name": "Users Name",
"username": "myusername",
"facebook_id": null,
"level": "1",
"birthdate": "1999-09-09T00:00:00+00:00",
"email": "user#gmail.com",
"activated": "",
"created": "2017-12-07T04:18:30+00:00",
"answers": [
{
"id": 31,
"question_id": 2,
"user_id": 2,
"answer": "School",
"questions": [
{
"id": 2,
"question": "Where did you meet your best friend?"
}
]
},
{
"id": 32,
"question_id": 3,
"user_id": 2,
"answer": "Dog",
"questions": [
{
"id": 3,
"question": "What was your first pet's name?"
}
]
}
]
}
],
"message": "Success"
}
Retrofit Interface class:
public interface RestInterface {
String url = "http://myurl.com";
/**
* Login
*
* #param username Username
* #param password Password
*
*/
#FormUrlEncoded
#Headers("User-Agent:My-Application")
#POST("login")
Call<userlogin> Login(#Field("username") String username,
#Field("password") String password);
}
Userlogin class:
public class userlogin {
#SerializedName("users")
#Expose
private List<users> users;
#SerializedName("message")
#Expose
private Object message;
public List<users> getUsers() {
return users;
}
public void setUsers(List<users> users) {
this.users = users;
}
public Object getMessage() {
return message;
}
public void setMessage(Object message) {
this.message = message;
}
}
users class:
public class users {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("username")
#Expose
private String username;
#SerializedName("facebook_id")
#Expose
private String facebookId;
#SerializedName("level")
#Expose
private String level;
#SerializedName("birthdate")
#Expose
private String birthdate;
#SerializedName("email")
#Expose
private String email;
#SerializedName("activated")
#Expose
private String activated;
#SerializedName("created")
#Expose
private String created;
#SerializedName("answers")
#Expose
private List<Answer> answers = null;
public users(){
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFacebookId() {
return facebookId;
}
public void setFacebookId(String facebookId) {
this.facebookId = facebookId;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public String getBirthdate() {
return birthdate;
}
public void setBirthdate(String birthdate) {
this.birthdate = birthdate;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getActivated() {
return activated;
}
public void setActivated(String activated) {
this.activated = activated;
}
public String getCreated() {
return created;
}
public void setCreated(String created) {
this.created = created;
}
public List<Answer> getAnswers() {
return answers;
}
public void setAnswers(List<Answer> answers) {
this.answers = answers;
}
}
Basically what happens is when it is called my "message" part comes back "Successful" which on my PHP side basically just states there were no errors. If there were any then it would return the error for display.
When trying to get the users information it always comes back with an empty List.
My response is always the same:
03-14 20:06:26.698 30995-30995/com.josh.testapp D/Response: {"message":"Success","users":[]}
03-14 20:06:26.699 30995-30995/com.josh.testapp I/System.out: Users:: []
03-14 20:06:26.699 30995-30995/com.josh.testapp D/Message: Success
I'm not sure what it is I'm missing. The users should be coming back as a list containing user information, in this case just the information of the user logging in. But in other parts, this will display sub-users information as well which is why it is in List form in the first place.
Please help or guide me in the right direction.
login.java (where the call is made)
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(RestInterface.url)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
RestInterface restInterface = retrofit.create(RestInterface.class);
Call<userlogin> call = restInterface.Login(
username.getText().toString(), // username
pass.getText().toString() // password
);
call.enqueue(new Callback<userlogin>() {
#Override
public void onResponse(Call<userlogin> call, retrofit2.Response<userlogin> response) {
if (response.isSuccessful()) {
userlogin ul = response.body();
try{
String res = new Gson().toJson(response.body());
Log.d("Response", res);
System.out.println("Users:: " + ul.getUsers().toString());
Log.d("Message", ul.getMessage().toString());
List<users> userList = ul.getUsers();
for(int i = 0; i < userList.size(); i++){
Log.d("Users", userList.get(i).getUsername());
}
} catch (Exception e){
Log.d("exception", e.getMessage());
}
} else {
Log.d("unSuccessful", response.message());
}
}
#Override
public void onFailure(Call<userlogin> call, Throwable t) {
Log.d("onFailure", t.getMessage());
}
});
After AbdulAli pointed out that it appeared to not be receiving the users list I decided to look over my code and run a few more tests on the server API. I discovered there was an issue with sessions. They weren't picking up and therefor returned a "Successful" yet empty user list. After implementing some CookieJar functions in I was able to pass my cookie for sessions and the user list was no longer empty.
While I feel like an idiot for missing something so obvious, I am very grateful for you pointing that out AbdulAli.