Web服务的JSON参数

时间:2014-09-01 06:08:16

标签: java json web-services rest json-simple

我正在尝试创建一个web service,它将在JSON response中进行,然后使用它查询数据库以返回商店详细信息(JSON response)

我打算稍后使用mobile app。但在开发过程中,我正在使用AJAX calls进行测试。我目前正在使用@GET请求。我能够成功返回JSON响应。我现在面临将JSON Object传递给@GET method的问题。在调试时,我看到输入参数中有一个空值。有人可以看看我的代码并告知我做错了吗?

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) {
    }
}

这是 offerProcess 类 -

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

对于它的价值,我使用 JSON.Simple库

4 个答案:

答案 0 :(得分:4)

假设您的input参数是GET请求的查询参数,那么您需要在参数中添加@QueryParam注释:

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

修改

但是,就像提到的@troylshields一样,如果您尝试发送JSON对象,则必须使用POST或PUT(具体取决于具体情况)。 GET请求仅支持查询参数,并且尝试通过查询参数发送JSON字符串不是一个好主意。

答案 1 :(得分:1)

尝试更改为POST。您没有通过GET请求将JSON正文传递给服务器。

答案 2 :(得分:1)

我能够像以下问题一样解决我的问题 - Json parameters are passed as null。另外,根据建议,我将@GET请求更改为@POST

我创建了一个名为 jsonFormat 的新类,它将接受@POST请求中传递的3个参数。

这是我的最终代码 -

    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) {
        }
    }

这是我创建的 jsonFormat 类 -

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

    }

最后, AJAX 代码 -

    <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>

感谢您的所有帮助和时间!我希望这对某些人有用。

答案 3 :(得分:0)

您的客户端代码不正确。您应该发送请求

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

在这种情况下,您的服务器部分input字符串将是正确的。

此外,正如我看到您发送POST请求,但服务器端需要GET请求