2013-08-31 23 views
8

Ciao, sto iniziando con i servizi Web in primavera, quindi sto cercando di sviluppare una piccola applicazione in Spring + JSON + Hibernate. Ho qualche problema con HTTP-POST. Ho creato un metodo:JSON post a Spring Controller

@RequestMapping(value="/workers/addNewWorker", method = RequestMethod.POST, produces = "application/json", consumes = "application/json") 
@ResponseBody 
public String addNewWorker(@RequestBody Test test) throws Exception { 
    String name = test.name; 
    return name; 
} 

E il mio modello di prova assomiglia a:

public class Test implements Serializable { 

private static final long serialVersionUID = -1764970284520387975L; 
public String name; 

public Test() { 
} 
} 

Con POSTINO io mando semplicemente JSON { "name": "TestName"} e ottengo sempre l'errore;

The server refused this request because the request entity is in a format not supported by the requested resource for the requested method. 

Ho importato la libreria di Jackson. I miei metodi GET funzionano bene. Non so cosa sto sbagliando. Sono grato per qualsiasi suggerimento.

+1

Quando hai inviato la richiesta utilizzando POSTMAN, specifichi l'intestazione "Content-type: application/json"? –

+0

Ok ora lavoro. Il mio problema era Content-type.E la mia seconda domanda. Come lavorare con le relazioni di entità in JSON Spring? Ho dipendenti di entità (quando ho riferimento all'indirizzo di classe) E JSON: { "indirizzo": {"strada": "asdas", "homeNo": "123", "flatNo": "123", " codice postale ":" 123 "," città ":" asdas "}," nome ":" asd "," email ":" asd "," pesel ":" 123 "," phone ":" asd "," employmentType ":" asd "," posizione ":" asd "," desc ":" asd " } E quando provo a inserire POST in oggetto Workers ottengo un errore precedente. Quello che sto facendo è sbagliato Grazie per le ultime risposte. – user2239655

+0

Hai specificato "Accetta: application/json" nell'intestazione? –

risposta

20

convertire il vostro oggetto JSON per JSON String utilizzando

JSON.stringify ({ "name": "TestName"})

o manualmente. @RequestBody mi aspetto una stringa json anziché un oggetto json.

Nota: la funzione stringa i avendo problema con una certa versione di IE, Firefox funzionerà

verificare la sintassi della richiesta Ajax per la richiesta POST. processData: falsa proprietà è necessaria nella richiesta AJAX

$.ajax({ 
    url:urlName, 
    type:"POST", 
    contentType: "application/json; charset=utf-8", 
    data: jsonString, //Stringified Json Object 
    async: false, //Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation 
    cache: false, //This will force requested pages not to be cached by the browser 
    processData:false, //To avoid making query String instead of JSON 
    success: function(resposeJsonObject){ 
     // Success Action 
    } 
}); 

controller

@RequestMapping(value = urlPattern , method = RequestMethod.POST) 

public @ResponseBody Test addNewWorker(@RequestBody Test jsonString) { 

    //do business logic 
    return test; 
} 

@RequestBody -Covert JSON oggetto java

@ResponseBody - convertire oggetto Java a JSON

+0

Come nascondere gli oggetti JSON Array ('[{a: 1}, {a: 2}]') su java? –

+0

@RequestBody non accetterà direttamente List/Array per cui è necessario creare una classe wrapper e impostare l'elenco su di essa. –

+0

La struttura dell'oggetto assomiglia a questa classe Test { \t ID intero; Elenco elenco persone; // getter and setters } JSON: {id: 1, personaLista: [{a: 1}, {a: 2}]} –

0

Provare a utilizzare l'applicazione/*. E utilizzare JSON.maybeJson() per verificare la struttura dei dati nel controller.

0

Non dimenticare di aggiungere ge tters e setters alla classe del tuo modello (nell'esempio la classe Test).

0

Effettuare le seguenti operazioni se si desidera utilizzare json come richiesta e risposta http. Quindi abbiamo bisogno di apportare modifiche in [contesto] .xml

<!-- Configure to plugin JSON as request and response in method handler --> 
<beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> 
    <beans:property name="messageConverters"> 
     <beans:list> 
      <beans:ref bean="jsonMessageConverter"/> 
     </beans:list> 
    </beans:property> 
</beans:bean> 
<!-- Configure bean to convert JSON to POJO and vice versa --> 
<beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> 
</beans:bean> 

MappingJackson2HttpMessageConverter alle messageConverters RequestMappingHandlerAdapter in modo che calci Jackson API in e converte JSON per Java Beans e viceversa. Avendo questa configurazione, useremo JSON nel corpo della richiesta e riceveremo i dati JSON nella risposta.

sto prevedendo anche piccolo frammento di codice per la parte di controllo:

@RequestMapping(value = EmpRestURIConstants.DUMMY_EMP, method = RequestMethod.GET) 

    public @ResponseBody Employee getDummyEmployee() { 
    logger.info("Start getDummyEmployee"); 
    Employee emp = new Employee(); 
    emp.setId(9999); 
    emp.setName("Dummy"); 
    emp.setCreatedDate(new Date()); 
    empData.put(9999, emp); 
    return emp; 
} 

Così nel precedente codice oggetto emp convertirà direttamente in JSON come risposta. lo stesso accadrà anche per posta.