1

I am trying to build a JSON string as server response with the aid of the Jackson library. If the route is not 0 I am getting tis response {"status":201,"routes":null} but I have problem to set the status variable to 204 in the SDBean class if the routeD is 0 I am getting in the console this output {"status":204,"routes":[1,9,3]} but in POSTMAN chrome extension the respose takes too long and I am getting this output The response status was 0. Check out the W3C XMLHttpRequest Level 2 spec for more details about when this happens. I want to get the following if routeD is not 0 to get {"status":201} else {"routes": {1,3,9}}

How can I manage that with Jakson?

Receiver class:

@Path("/data")
public class Receiver {

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public Response storeData(Data data) {
        Database db = new Database();

        String macD = data.getMac();
        int routeD = data.getRoute();
        double latD = data.getLatitude();
        double longD = data.getLongitude();
        double speedD = data.getSpeed();

        SDBean bean = new SDBean();
        if (routeD != 0) {
            bean.status = db.insertData(macD, routeD, latD, longD);
            return Response.status(bean.status).entity(bean.toJson()).build();

        } else {
            bean.routes = db.detectRoute(latD, longD);
            return Response.status(bean.status).entity(bean.toJson()).build();

        }

    }

}

SDBean class:

import java.util.ArrayList;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class SDBean {

    public int status;
    public ArrayList<Integer> routes;

    public String toJson() {

        ObjectMapper mapper = new ObjectMapper();
        String json = null;

        if(status == 0){
            this.status = 204;
        }

        try {
            json = mapper.writeValueAsString(this);
        } catch (JsonProcessingException e) {
            e.printStackTrace();

        }
        return json;
    }

}

1 Answer 1

1

Your problem with 0 response due to you don't initialize your int value inside bean. When you try to analize your code :

//Inside Receiver 
return Response.status(bean.status).entity(bean.toJson()).build();

In this line you first get value from status field from bean. It's initialize with default value of 0 (Oracle documentation about primitive data types and default values) and next you map it toJson() where you set it's value to status response 204 in this line :

//Inside SDBean
if(status == 0){
    this.status = 204;
}

I suggest one of this resulutions:

  1. Initialize variable inline:

    public int status = 204;

  2. If you need some additional logic you could use static initialization block

    static {
        //additional logic here
        status = 204;
    }
    
  3. Or simply use constructor in your case:

    public SDBean(){
        //additional logic here
        status = 204;
    }
    

For more info here you have documentation: Initializing fields.

Also you don't add anything to your ArrayList. Try to initialize it inside your bean inline:

public ArrayList<Integer> routes = new ArrayList<Integer>();

or if you use jdk 1.7+ use diamond interfece instead

public ArrayList<Integer> routes = new ArrayList<>();

And now you can use it to add your data inside storeData class:

bean.routes.add(yourIntValue);

// EDIT:

package com.gmail.at.mironiuk.kacper.stack.overflow.wtf;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/data")
public class Receiver {

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public Response storeData(Data data) {
        Database db = new Database();
        SDBean bean = new SDBean();

        String macD = data.getMac();
        int routeD = data.getRoute();
        double latD = data.getLatitude();
        double longD = data.getLongitude();
        double speedD = data.getSpeed();

        if (routeD != 0) { // here you always will have null or empty case you only set your status here
            bean.status = db.insertData(macD, routeD, latD, longD); // In this if try to add sth to your list
            bean.status = 204;
            return Response.status(bean.status).entity(bean.toJson()).build(); //Expected result {"status":"204", "routes": []}
        } else { // here your List will be this whats you returns from
            bean.routes = db.detectRoute(latD, longD); // <- this function and i don't know what function returns
            return Response.status(bean.status).entity(bean.toJson()).build(); //Expected result {"status":"204", "routes": [?,?,?]}
        }
    }

}

I hope that I help you

Sign up to request clarification or add additional context in comments.

5 Comments

I have initialized it I am not getting this error The response status was 0 in POSTMAN anymore but there is a strange behavior I cant see the output {"status":204,"routes":[1,9,3]} which is in the eclipse console in POSTMAN there I am getting just a small 1 but if routeD ist not 0 I am getting in eclipse console as well in POSTMAN the following {"status":201,"routes":null} ?
Use annotation @Produces("application/json")
And also I cannot see that you something add in your 'ArrayList'. Try to initialize 'new ArrayList<Integer>()' inline inside your bean and use 'bean.routes.add(yourValue)'
I added @Produces ... and initialized the routes ArrayList but I dont know where I should use bean.routes.add(yourIntValue); .As I said I just have the problem in case of routeD=0 the response is not being sent to the client but it is being output in eclipse console I am getting this output {"status":204,"routes":[1,9,3]}
It is since 204 Http code status The server successfully processed the request, but is not returning any content. Usually used as a response to a successful delete request..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.