Spring+Servlet返回Json给安卓客户端并解决中文乱码问题

0 首先Spring的配置,以及一些JavaBean和Dao的配置比较简单,不在赘述,这里说明一些关键问题。


1 Spring使用声明式事务,进行Dao和Service方法的依赖注入而在Servlet中不能使用声明式事务,解决方法:
     在Servlet的Init方法中使用编程式事务:
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 在servlet的doGet方法中:
//ListService是Service类主要包括一些查询数据库的操作,返回的是一个List
		List<FoodList> foodList=listService.findAll();
		Iterator<FoodList> foodIterator=foodList.iterator();
		
		//下面代码生成Json
		JSONObject outList = null;
		try {
			// 首先最外层是{},是创建一个对象  
		    outList = new JSONObject();   
		    // 键list1的值是对象,所以又要创建一个对象  
		    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);

  在doGet方法中关键是
byte[] b=outList.toString().getBytes("UTF-8");
		response.getOutputStream().write(b);
这句代码,因为在mysql中设置的数据库为utf-8格式,所以这里必须设置为UTF-8格式,否则json中文乱码。

3 在安卓客户端解析json代码:
URL url = new URL(Url);
		        HttpURLConnection connection = (HttpURLConnection) url
		                .openConnection();
		        connection.setRequestMethod("GET");
		        // 填入apikey到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);


总结:完成了Sring和spring JDBC和Servlet作为服务端,给Json返回数据的基本框架,并且解决了解析的json中文乱码的问题。
 

猜你喜欢

转载自icesnowwolf8201604130939.iteye.com/blog/2302024