2009-04-02 14 views
10

Ho problemi using Gzip compression and JQuery together. Sembra che possa essere causato dal modo in cui sto inviando risposte JSON nelle mie azioni Struts. Io uso il prossimo codice per inviare i miei oggetti JSON indietro.Come inviare JSON indietro con JAVA?

public ActionForward get(ActionMapping mapping, 
    ActionForm  form, 
    HttpServletRequest request, 
    HttpServletResponse response) { 
     JSONObject json = // Do some logic here 
     RequestUtils.populateWithJSON(response, json); 
     return null;    
} 

public static void populateWithJSON(HttpServletResponse response,JSONObject json) { 
    if(json!=null) { 
     response.setContentType("text/x-json;charset=UTF-8");   
     response.setHeader("Cache-Control", "no-cache"); 
     try { 
      response.getWriter().write(json.toString()); 
     } catch (IOException e) { 
      throw new ApplicationException("IOException in populateWithJSON", e); 
     }        
    } 
} 

C'è un modo migliore di inviare JSON in un'applicazione Web Java?

+1

Ho usato response.setContentType ("application/json; charset = UTF-8"); invece di response.setContentType ("text/x-json; charset = UTF-8"); – bentzy

risposta

14

Invece di

try { 
     response.getWriter().write(json.toString()); 
} catch (IOException e) { 
     throw new ApplicationException("IOException in populateWithJSON", e); 
}   

provare questo

try { 
     json.write(response.getWriter()); 
} catch (IOException e) { 
     throw new ApplicationException("IOException in populateWithJSON", e); 
}          

perché questo permetterà di evitare la creazione di una stringa e il JSONObject sarà direttamente scrivere i byte all'oggetto Writer

+0

Sto lavorando su qualcosa di simile, quale libreria viene utilizzata per importare json.write()? – codeBarer

+0

usa il mappatore di jackson da http://jackson.codehaus.org/ – Ram

1

Personalmente, penso che utilizzando JAX-RS è il modo migliore per gestire l'associazione dei dati, che sia XML o JSON. Jersey è una buona implementazione JAX-RS (anche RestEasy è buono) e ha un buon supporto. In questo modo puoi usare oggetti reali, senza bisogno di usare classi proprietarie di lib di Json.org.

0

response.getWriter(). scrivere (json.toString());

passare a: response.getWriter(). stampa (json.toString());

+0

uhm, solo per scrivere qualcosa? –

Problemi correlati