2009-04-02 2 views
10

Tôi gặp sự cố using Gzip compression and JQuery together. Dường như nó có thể được gây ra bởi cách tôi gửi phản hồi JSON trong hành động Struts của tôi. Tôi sử dụng mã tiếp theo để gửi các đối tượng JSON của tôi trở lại.Làm thế nào để gửi JSON trở lại với 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ó cách nào tốt hơn để gửi JSON trong ứng dụng web Java không?

+1

Tôi đã sử dụng response.setContentType ("application/json; charset = UTF-8"); thay vì response.setContentType ("văn bản/x-json; charset = UTF-8"); – bentzy

Trả lời

14

Thay vì

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

thử này

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

vì điều này sẽ tránh tạo ra một chuỗi và JSONObject sẽ trực tiếp viết các byte đến đối tượng Writer

+0

Tôi đang làm việc trên một cái gì đó tương tự, thư viện nào được sử dụng để nhập json.write()? – codeBarer

+0

sử dụng trình lập bản đồ jackson từ http://jackson.codehaus.org/ – Ram

1

Cá nhân, tôi nghĩ rằng sử dụng JAX-RS là cách tốt nhất để đối phó với ràng buộc dữ liệu, đó là XML hoặc JSON. Jersey là một cài đặt JAX-RS tốt (RestEasy cũng tốt) và có hỗ trợ tốt. Bằng cách đó bạn có thể sử dụng các đối tượng thực, không cần sử dụng các lớp độc quyền của Json.org libs.

0

response.getWriter(). viết (json.toString());

đổi thành: response.getWriter(). in (json.toString());

+0

uhm, chỉ để viết một cái gì đó? –