Send arraylist from servlet to android app

How can I send a list of arrays from a servlet to an android app?

+6
source share
2 answers

To do this, you need to convert it to String in some standard format, which can then be parsed and created using existing libraries. For example, JSON, XML or CSV, all of which are standardized and pluggable string formats, for which there are many parsing / building libraries in many programming languages.

Android has a built-in JSON parser in the org.json package . It has a built-in XML parser in the org.xml.sax package . I'm not sure if there is a built-in CSV library, but it seems not. Java EE has a great built-in XML parser in the JAXB flavor, but it doesn't have a built-in JSON parser. Only JAX-RS versions (Jersey, RESTeasy, etc.) Provide a JSON parser. If you can change your servlet as a JAX-RS web service, it will be beneficial for you to return both XML and JSON with minimal effort. See also Servlet vs RESTful .

Which format to choose depends on the only functional requirements. For example, should a servlet be reused for other services? What are the target customers? Etcetera.

In any case, the JSON format is usually more concise and more popular recently than XML, so I’ll just give an example run that passes data in JSON format, and I’ll assume that you really want to do this with a simple vanilla servlet instead of JAX-RS . In this example, you only need to load and drop the JSON library, such as Gson in /WEB-INF/lib , in order to convert Java objects to JSON in the servlet.

 @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<String> list = new ArrayList<String>(); list.add("item1"); list.add("item2"); list.add("item3"); String json = new Gson().toJson(list); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(json); } 

This will build and return the List in the following JSON format:

 ["item1","item2","item3"] 

This, in turn, is handled by the org.json API in Android as follows:

 String jsonString = getServletResponseAsStringSomehow(); // HttpClient? JSONArray jsonArray = new JSONArray(jsonString); List<String> list = new ArrayList<String>(); for (int i = 0; i < jsonArray.length(); i++) { list.add(jsonArray.getString(i)); } // Now you can use `list`. 
+5
source

If its pull-based model, you can send a GET HTTP request to the servlet endpoint from your Android application, and the HTTP response can be a JSON object created from a list of arrays.

+1
source

Source: https://habr.com/ru/post/902522/


All Articles