2013-09-29 19 views
12

Sto cercando di inviare alcuni dati JSON tramite jquery POST a un servizio REST jersey nel mio computer locale.Jersey consuma JSON su POST

Dal lato server, ho il metodo Jersey per utilizzare questo JSON che viene POSTATO.

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

    } 


} 

Sto avvolgendo i dati JSON su richiesta. In modo che nel server, posso ottenere tutti i dati inviati in richiesta in quella classe wrapper. La mia classe wrapper per la richiesta è

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 + "]"; 
    } 



} 

Il POJO questione di classe

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

    } 


} 

Ogni volta che faccio una richiesta dal jquery come illustrato di seguito,

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

       } 
      }); 

    } 

ottengo questo errore nel console:

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: [email protected]; line: 1, column: 16] (through reference chain: com.netsquid.tqa.entity.TQARequest["tqaRequest"]) 

Posso risolvere questo problema inviando la domanda json da jquery e accettando il parametro domanda nel metodo. Ma ho bisogno di racchiudere tutte le richieste jquery in TQARequest e accettare tutte le richieste come TQARequest e quindi estrarre l'oggetto domanda da esso. Come faccio a fare questo ?

mio mappatura POJO in web.xml è:

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

risposta

7

Credo che è possibile semplificare il documento JSON come segue:

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

E 'ancora un oggetto "tqaRequest" in questa forma.

Se si desidera supportare un elenco di domande, la vostra JSON potrebbe assomigliare a questo (gli array JSON vanno parentesi all'interno quadrati):

{ 
    "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" 
     }] 
    } 
} 

E si sarebbe regolare la classe TQARequest fare riferimento a:

private List<Question> questions; 

anziché

private Question question; 
+0

Ma cosa succede se, ho bisogno di più di un livello di JSON? es: { "Q1": { "domanda": { "createdOn": "sfddsf", "questionText": "fsdfsd", "questionTrackingURL": "http://www.google. com ", " questionURL ":" ssdf " } } } – cherit

+0

Se si aggiunge un altro livello, è necessario eseguire il mirror del modello di oggetto Java.Quindi in questo caso avresti un oggetto TQARequest, avvolgendo un oggetto Q1, avvolgendo un oggetto Question. Puoi essere più specifico, però, su cosa vuoi fare? Vuoi inserire un elenco di domande? –

+0

Sì, ho bisogno di prendere in una lista di domande tutto incluso nell'oggetto TQARequest dalla mia pagina html in json. – cherit

3

Hope this risolve il problema.

@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()); 
} 
} 
+2

@Consumi (MediaType.APPLICATION_JSON), ma l'argomento è String. Quindi dovrei consumare MediaType.PLAINTEXT? , Ma questo spezzerà le mie specifiche REST, preferisco che il produttore e il consumatore siano in JSON. – cherit

+0

non sono sicuro, io il mio caso produce 'JSON' ma non ho specificato' @ Consumi', funziona bene per me. Hai provato con il tuo attuale set-up? es., con '@ Consumi' come' JSON' e argomento come String. –

+0

Penso che la questione non fosse come mappare json-string per oggetti manualmente, ma piuttosto su come configurare Jersey per mappare automaticamente a TQARequest. – iTollu