Spring+Servlet returns Json to the Android client and solves the problem of Chinese garbled characters

0 First of all, the configuration of Spring, as well as the configuration of some JavaBeans and Dao is relatively simple, so I won't go into details. Here are some key issues.


1 Spring uses declarative transactions to perform dependency injection of Dao and Service methods and cannot use declarative transactions
     in Servlets. The solution: use programmatic transactions in the Init method of Servlet:
public void init() throws ServletException {
		// Put your code here
		     super.init();   
        
	       ServletContext servletContext = this .getServletContext();   
	                 
	       WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);   
	                 
	       listService = (ListService)ctx.getBean("listService" );   
	}

2 In the doGet method of the servlet:
//ListService is a Service class that mainly includes some operations to query the database, and returns a List
		List<FoodList> foodList=listService.findAll();
		Iterator<FoodList> foodIterator=foodList.iterator();
		
		//The following code generates Json
		JSONObject outList = null;
		try {
			// First the outermost layer is {}, which is to create an object  
		    outList = new JSONObject();   
		    // The value of the key list1 is an object, so we need to create another object  
		    JSONObject inerList = new JSONObject ();  
		    JSONArray ifo = new JSONArray();
		    while(foodIterator.hasNext()){
		    	FoodList food=foodIterator.next();
		    	inerList.put("id", food.getId());
				inerList.put("name", food.getName());
				inerList.put("img", food.getImg());	
				ifo.put (inerList);
		    }
		    outList.put("status",true);
		    outList.put("total",101254);
		    outList.put("tngou", ifo);
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		byte[] b=outList.toString().getBytes("UTF-8");
		response.getOutputStream().write(b);

  In the doGet method the key is
byte[] b=outList.toString().getBytes("UTF-8");
		response.getOutputStream().write(b);
This code, because the database set in mysql is in utf-8 format, it must be set to UTF-8 format here, otherwise the json Chinese is garbled.

3 Parse the json code on the Android client:
URL url = new URL(Url);
		        HttpURLConnection connection = (HttpURLConnection) url
		                .openConnection();
		        connection.setRequestMethod("GET");
		        // Fill in apikey into HTTP header
		        //connection.setRequestProperty("apikey",  "your apikey");
		        connection.connect();
		        InputStream is = connection.getInputStream();
		        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
		        String strRead = null;
		        while ((strRead = reader.readLine()) != null) {
		            sbf.append(strRead);
		            sbf.append("\r\n");
		        }
		        reader.close();
		        result = sbf.toString();
		    } catch (Exception e) {
		        e.printStackTrace ();
		    }
		    try {
		    	MeiShi item;
				JSONObject jsonObject=new JSONObject(result);
				JSONArray jsonArray=jsonObject.getJSONArray("tngou");
				for(int i=0;i<jsonArray.length();i++)
				{
					item=new MeiShi();
					jsonObject =jsonArray.getJSONObject(i);					
					item.setName(jsonObject.getString("name"));			
					item.setImg(jsonObject.getString("img"));
					//item.setKeywords(jsonObject.getString("keywords"));
					//item.setCount(jsonObject.getString("count"));
					item.setId(jsonObject.getString("id"));
					resultList.add(item);


Summary: Completed the basic framework of Sring and spring JDBC and Servlet as the server to return data to Json, and solved the problem of parsed json Chinese garbled.
 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326723664&siteId=291194637