JSON parameter for web service

I am trying to create web service

to be executed in JSON response

and then query the DB with it to return the store data (JSON response)

.

I intend to use this later with mobile app

. But during development I test with AJAX calls

. I am currently using query @GET

. I was able to successfully return a JSON response. Now I am facing the problem of transferring JSON Object

to @GET method

. When debugging, I see that there is a null value in my input parameter. Can anyone take a look at my code and advise what I am doing wrong?

import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;

import java.util.Iterator;

import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.JSONValue;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

/**
 * REST Web Service
 *
 * @author Aj
 *
 * This service will return the offers valid for the IMSI number passed
*/
@Path("getOffers")
public class GetOffersResource {

    @Context
    private UriInfo context;

    /**
    * Creates a new instance of GetOffersResource
     */
    public GetOffersResource() {
    }

    @GET
    @Consumes("application/json")
    @Produces("application/json")
    public String getJson(final String input) {

        JSONParser parser = new JSONParser();
        String[] response = new String[5];

        try {
            Object obj = parser.parse(input);
            JSONObject jsonObject = (JSONObject) obj;
            offerProcess ofc = new offerProcess();
            ofc.setLatitude((double) jsonObject.get("latitude"));
            ofc.setLongitude((double) jsonObject.get("longitude"));
            ofc.setIMSI((long) jsonObject.get("IMSI"));

            response = ofc.fetchOffers();

        } catch (ParseException e) {
            JSONObject ser = new JSONObject();

            ser.put("status", "error");
            ser.put("reason", "Bad request");

            return ser.toJSONString();
        }

        //TODO return proper representation object
        JSONObject ser = new JSONObject();
        JSONArray arr = new JSONArray();

        arr.add("456TYU");
        arr.add("OLED TV");
        arr.add("24-JUL-2014");
        arr.add("XYZ Enterprises");
        arr.add("Gachibowli");
        arr.add("9911278366");

        ser.put("status", "success");
        ser.put("Offers", arr);

        System.out.println(ser);

        return ser.toJSONString();
    }

    /**
     * PUT method for updating or creating an instance of GetOffersResource
     *
     * @param content representation for the resource
     * @return an HTTP response with content of the updated or created resource.
     */
    @PUT
    @Consumes("application/json")
    public void putJson(String content) {
    }
}

      

Here is the offerProcess class -

public class offerProcess {

    private double longitude;
    private double latitude;
    private long IMSI;

    public double getLongitude() {
        return longitude;
    }

    public double getLatitude() {
        return latitude;
    }

    public void setLongitude(double longitude) {
        this.longitude = longitude;
    }

    public void setLatitude(double latitude) {
        this.latitude = latitude;
    }

    public long getIMSI() {
        return IMSI;
    }

    public void setIMSI(long IMSI) {
        this.IMSI = IMSI;
    }

    public String[] fetchOffers(){
        String[] response = new String[5];

        response[0] = "456TYU";
        response[1] = "OLED TV";
        response[2] = "24-JUL-2014";
        response[3] = "XYZ Enterprises";
        response[4] = "Gachibowli";
        response[5] = "9980556990";

        return response;
    }
}

      

For what it's worth, I'm using the JSON.Simple library .

+3


source to share


4 answers


I managed to solve my problem by doing the same as in the next question - Json parameters are passed as null . Also as suggested I changed from @GET

request to @POST

.

I created a new class called jsonFormat that will accept three parameters passed in the request @POST

.

Here is my final code that works -

    import javax.ws.rs.core.Context;
    import javax.ws.rs.core.UriInfo;
    import javax.ws.rs.PathParam;
    import javax.ws.rs.Produces;
    import javax.ws.rs.Consumes;
    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.PUT;
    import javax.ws.rs.POST;

    import java.util.Iterator;

    import org.json.simple.JSONObject;
    import org.json.simple.JSONArray;
    import org.json.simple.JSONValue;
    import org.json.simple.parser.JSONParser;
    import org.json.simple.parser.ParseException;

    /**
     * REST Web Service
     *
     * @author Aj
     *
     * This service will return the offers valid for the IMSI number passed
     */
    @Path("getOffers")
    public class GetOffersResource {

        @Context
        private UriInfo context;

        /**
         * Creates a new instance of GetOffersResource
         */
        public GetOffersResource() {
        }

        @POST
        @Consumes("application/json")
        @Produces("application/json")
        public String getJson(jsonFormat jsonObj) {

            String[] response = new String[5];

            offerProcess ofc = new offerProcess();

            try {

                ofc.setLatitude(jsonObj.latitude);
                ofc.setLongitude(jsonObj.longitude);
                ofc.setIMSI(jsonObj.IMSI);

            } catch (Exception e) {
                JSONObject ser = new JSONObject();

                ser.put("status", "error");
                ser.put("reason", jsonObj.latitude);

                return ser.toJSONString();
            }

            //TODO return proper representation object
            JSONObject ser = new JSONObject();
            JSONArray arr = new JSONArray();

            arr.add("456TYU");
            arr.add("OLED TV");
            arr.add("24-JUL-2014");
            arr.add("XYZ Enterprises");
            arr.add("Gachibowli");
            arr.add("9911278366");

            ser.put("status", "success");
            ser.put("Offers", ofc.getIMSI());

            System.out.println(ser);

            return ser.toJSONString();
        }

        /**
         * PUT method for updating or creating an instance of GetOffersResource
         *
         * @param content representation for the resource
         * @return an HTTP response with content of the updated or created resource.
         */
        @PUT
        @Consumes("application/json")
        public void putJson(String content) {
        }
    }

      

Here is the jsonFormat class I created -



    import javax.xml.bind.annotation.XmlRootElement;

    /**
     *
     * @author Aj
     * This class forms the format of the JSON request which will be recieved from the App
     */
    @XmlRootElement
    public class jsonFormat {
        public double longitude;
        public double latitude;
        public long IMSI;

        jsonFormat(){}

        jsonFormat(double longitude,double latitude, long IMSI){
            this.longitude = longitude;
            this.latitude = latitude;
            this.IMSI = IMSI;
        }

    }

      

Finally, the AJAX code -

    <script type="text/javascript">

        var url1 = "http://localhost:8080/Offers/webresources/getOffers";

        var requestData = {"longitude": "77.681307",
            "latitude": "12.8250278",
            "IMSI": "404490585029957"};

        var jsonObj = JSON.stringify(requestData);

        $.ajax({
            type: "POST",
            contentType: "application/json",
            url: url1,
            async: true,
            data: jsonObj,
            success: function(response) {

                //var obj = JSON.parse(response);
                console.log(response.status);
                console.log(response.reason);
                console.log(response.Offers);
            }
        });
    </script>

      

Thanks for your help and time! Hope this might be helpful to someone.

+1


source


Assuming your parameter input

is a request parameter for a GET request, you need to add an annotation @QueryParam

to the parameter:

    @GET
    @Consumes("application/json")
    @Produces("application/json")
    public String getJson(@QueryParam("input") final String input) {
          ...
    }

      



Edit:

However, as @troylshields mentioned, if you are trying to send a JSON object, you must use POST or PUT (as appropriate). GET request only supports a query parameter, and trying to send a JSON string using a query parameter is not a good idea.

+4


source


Try to go to POST. You are not passing the JSON body to the server with a GET request.

+1


source


Your client code is incorrect. You must send the request as

var requestData = {"longitude" : "77.681307",  "latitude"  : "12.8250278", "IMSI": "404490585029957"};    
// ...  
$.ajax({
// ...
   data: {input : requestData}  // 'input' should be the root element  
// ...
)}; 

      

In this case, the string input

will be correct on your server side .

Also, as I can see you are sending a request POST

, but the request GET

is expected on the server side

0


source







All Articles