日期:2014-05-16  浏览次数:20429 次

使用gson获取json对象

以下是一个省市级联的的例子:

文本框里的内容:

<select class="text" name="district_id"
???????????onchange="getStreet(this.value);">
???????????<option value="-1">
????????????请选择所属区
???????????</option>
???????????<c:forEach var="districName"
????????????items="${requestScope.districList}">
????????????<option value="${districName.id}">
?????????????${districName.name}
????????????</option>
???????????</c:forEach>
??????????</select>
??????????街:
??????????<select class="text" name="street_id" id="street">
???????????<option>
????????????请选择街道
???????????</option>
??????????</select>

js里:

?<script type="text/javascript">
??function getStreet(districtId){
????var url = "getStreet2.action";
???var postData = {districtId:districtId};
???$.getJSON(url,postData,function(data){
????$("#street").empty();
????$.each(data,function(i){
?????var item = data[i];
?????var option = $("<option value='"+item.districtId+"'>"+item.name+"</option>");
?????$("#street").append(option);
????});
???});
??}
?</script>

action里:

?Gson gson=new Gson();
??String json=gson.toJson(obj);
??response.setCharacterEncoding("utf-8");
??try {
???response.getWriter().write(json);
??} catch (IOException e) {
???e.printStackTrace();
??}