Jersey在POST上使用JSON

时间:2013-09-29 22:06:58

标签: java jquery json rest jersey

我正在尝试通过jquery POST将一些json数据发送到本地计算机上的泽西REST服务。

在我的服务器端,我使用Jersey方法来使用POST的这个JSON。

@Path("/question")
public class QuestionAPI {


    private final static Logger LOGGER = Logger.getLogger(HelloWorldApi.class .getName());

     @POST
     @Path("/askquestion")
     @Produces(MediaType.APPLICATION_JSON)
     @Consumes(MediaType.APPLICATION_JSON)
     public TQARequest askquestion(TQARequest tqaRequest, @Context HttpServletRequest request) {

         LOGGER.info("Inside-->askquestion-->TQARequest"+tqaRequest.getQuestion());

         return tqaRequest;

     }


}

我正在请求中包装json数据。因此,在服务器中,我可以在该包装类中获取请求中发送的所有数据。我的请求包装类是

public class TQARequest {

    private Question question;

    public Question getQuestion() {
        return question;
    }

    public void setQuestion(Question question) {
        this.question = question;
    }

    @Override
    public String toString() {
        return "TQARequest [question=" + question + "]";
    }



}

问题pojo类

public class Question {

    @Id
    private Long questionID;

    private String questionText;

    private long createdOn;

    private String questionURL;

    private String questionTrackingURL;

    @Override
    public String toString() {
        return "Question [questionID=" + questionID + ", questionText="
                + questionText + ", createdOn=" + createdOn + ", questionURL="
                + questionURL + ", questionTrackingURL=" + questionTrackingURL
                + "]";
    }

    public Question(String questionText, long createdOn, String questionURL,
            String questionTrackingURL) {
        super();
        this.questionText = questionText;
        this.createdOn = createdOn;
        this.questionURL = questionURL;
        this.questionTrackingURL = questionTrackingURL;
    }

    public Long getQuestionID() {
        return questionID;
    }

    public void setQuestionID(Long questionID) {
        this.questionID = questionID;
    }

    public String getQuestionText() {
        return questionText;
    }

    public void setQuestionText(String questionText) {
        this.questionText = questionText;
    }

    public long getCreatedOn() {
        return createdOn;
    }

    public void setCreatedOn(long createdOn) {
        this.createdOn = createdOn;
    }

    public String getQuestionURL() {
        return questionURL;
    }

    public void setQuestionURL(String questionURL) {
        this.questionURL = questionURL;
    }

    public String getQuestionTrackingURL() {
        return questionTrackingURL;
    }

    public void setQuestionTrackingURL(String questionTrackingURL) {
        this.questionTrackingURL = questionTrackingURL;
    }

    public Question(){

    }


}

每当我从jquery发出请求时,如下所示,

 function askQuestion(){


        $.ajax({
              type: "POST",
              contentType: "application/json; charset=utf-8",
              url: "/api/question/askquestion",
              data: 
               JSON.stringify({
                   "tqaRequest" : {
                          "question" : {
                             "createdOn" : "sfddsf",
                             "questionText" : "fsdfsd",
                             "questionTrackingURL" : "http://www.google.com",
                             "questionURL" : "ssdf"
                          }
                       }
                    }

                     ),
              dataType: "json",
              success: function(response){

                  console.log(response);

              }
            });  

    }

我在控制台中收到此错误:

WARNING: /api/question/askquestion: org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "tqaRequest" (Class com.netsquid.tqa.entity.TQARequest), not marked as ignorable
 at [Source: org.mortbay.jetty.HttpParser$Input@899e3e; line: 1, column: 16] (through reference chain: com.netsquid.tqa.entity.TQARequest["tqaRequest"])

我可以通过从jquery发送Question json并接受方法中的question参数来解决这个问题。 但我需要在TQARequest中包装所有jquery请求并接受所有请求作为TQARequest,然后从中提取问题对象。我该怎么做?

我在web.xml中的POJO映射是:

    <init-param>
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
        <param-value>true</param-value>
    </init-param>

2 个答案:

答案 0 :(得分:7)

我相信您可以按如下方式简化JSON文档:

{
    "question" : {
        "createdOn" : "sfddsf",
        "questionText" : "fsdfsd",
        "questionTrackingURL" : "http://www.google.com",
        "questionURL" : "ssdf"
    }
}

这种形式仍然是“tqaRequest”对象。

如果你想支持一系列问题,你的JSON可能看起来像这样(JSON数组放在方括号内):

{
    "questions" : [
        {
            "createdOn" : "date 1",
            "questionText" : "question 1",
            "questionTrackingURL" : "http://www.google.com",
            "questionURL" : "question 1 url"
        },
        {
            "createdOn" : "date 2",
            "questionText" : "question 2",
            "questionTrackingURL" : "http://www.google.com",
            "questionURL" : "question 2 url"
        }]
    }
}

你会调整你的TQARequest类来引用:

private List<Question> questions;

而不是

private Question question;

答案 1 :(得分:4)

希望这能解决问题。

@POST
@Path("/askquestion")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public TQARequest askquestion(String jsonRequest){       
         TQARequest tqaRequest = MapperUtil
                                  .readAsObjectOf(TQARequest.class, jsonRequest);
    }

<强> MapperUtil.java

com.fasterxml.jackson.databind.ObjectMapper MAPPER = new ObjectMapper();

 public static <T> T readAsObjectOf(Class<T> clazz, String value)
          throws MYPException {
 try {
      return MAPPER.readValue(value, clazz);
      } catch (Exception e) {
      LOGGER.error("{}, {}", e.getMessage(), e.fillInStackTrace());
 }
}