从服务端获取json格式参数的解析。
1、普通Json格式
服务端:
String json = json = "{\"code\":\"1\",\"result\":\"1\"}";
out.print(json);
out.flush();
out.close();
客户端解析:
链接服务端获取到字符串:
HttpPost post = new HttpPost(serverURL); //创建HttpPost对象
HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8"); //使用UTF-8编码方式
post.setEntity(entity); //设置编码方式
HttpResponse response = new DefaultHttpClient().execute(post); //执行HttpClient post请求
int sCode = response.getStatusLine().getStatusCode();
if (sCode == HttpStatus.SC_OK) { //请求成功
String stringJson = EntityUtils.toString(response.getEntity());
} else
throw new Exception("StatusCode is " + sCode); //抛出异常信息
JSONObject entitys = new JSONObject(stringJson);
String code = entitys.getString("code");
String result = entitys.getString("result");
<p>2、多层Json</p><p>服务端:</p><pre class="java" name="code">String json = "{\"code\":\"1\",\"result\":{\"interceptorB\":\""+interceptorBrowser+"\",\"interceptorP\":\""+interceptorPath+"\",\"status\":\"300\"}}";
out.print(json);
out.flush();
out.close();
客户端解析:
<pre class="java" name="code">JSONObject result = json.getJSONObject("result");
String interceptorB = result.getString("interceptorB");
String status = result.getString("status");
3、JSON数组解析
服务端:
StringBuffer strreturn = new StringBuffer();
strreturn.append("{\"result\":true,\"count\":")
.append(list.size())
.append(",\"data\":[");
for (int i = 0; i < list.size(); i++) {
strreturn.append("{\"mobile\":\"")
.append(info.getMobile())
.append("\",\"linkid\":\"")
.append(info.getLinkid())
.append("\"");
if(i==list.size()-1)
strreturn.append("}");
else
strreturn.append("},");
}
strreturn.append("]}");
out.clear();
out.println(strreturn.toString());
out.flush();}
客户端接收:
JSONObject entries = new JSONObject(jsonString);
JSONArray dataArray = entries.getJSONArray("data");
final int ARRAY_LENGTH = dataArray.length();
for (int i = 0; i < ARRAY_LENGTH; i++) {
final JSONObject jsonObject = dataArray.getJSONObject(i);
String mobile = jsonObject.getString("mobile");
String linkid = jsonObject.getSyring("linkid");
}