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中文乱码的问题。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值