JSON是一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特点。
android中的JSON解析部分都在org.json下。主要有以下几个类:
1、JOSNObject:json对象
2、JSONStringer:JOSN文本构建类
3、JSONArray :一组有序的数值
解析json数据格式方法(返回一个list):
public static List<String> jsonToList(String data)
{
List<String> cities = new ArrayList<String>();
try
{
JSONObject jsonObject = new JSONObject(data);
JSONArray jsonArray = jsonObject.getJSONArray("person");
for(int i = 0; i < jsonArray.length(); i++)
{
cities.add(jsonArray.getString(i));
}
}
catch (Exception e)
{
e.printStackTrace();
}
return cities;
}
服务器向客户端发送Json数据:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter writer = response.getWriter();
String type = request.getParameter("type");
if("json".equals(type))
{
List<String> person= new ArrayList<String>();
person.add("小明");
person.add("小华");
person.add("二蛋");
person.add("lzb");
Map<String, List<String>> map = new HashMap<String, List<String>>();
map.put("person", person);
String citiesString = JSON.toJSONString(map);
writer.println(citiesString);
}
writer.flush();
writer.close();
}
}