我是json解析的新手...请帮我解析android中的以下代码
{"msg":[{"msg":[{"message":"hi","sender":"C"},{"message":"sd","sender":"A"},
{"message":"herold","sender":"C"},{"message":"s","sender":"A"},
{"message":"tu","sender":"A"},{"message":"xx","sender":"A"},{"message":"re","sender":"A"},
{"message":"tt","sender":"A"},{"message":"yo","sender":"A"},{"message":"ty","sender":"A"},
{"message":"tgtttt","sender":"A"},{"message":"gggggg","sender":"A"},
{"message":"don","sender":"A"},{"message":"eee","sender":"A"},
{"message":"iit","sender":"A"},{"message":"tttt","sender":"A"},
{"message":"yuio","sender":"A"}],"index":"128","uid":"a8f15eda80c50adb0e71943adc8015cf"}]}
答案 0 :(得分:2)
使用以下方法获取您的回复:
public static String getWebserviceResponse(String p_url) {
String m_response = null;
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(p_url);
HttpResponse response;
System.err.println("Request URL---------->"+ p_url);
try {
response = client.execute(httpget);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
InputStream in = response.getEntity().getContent();
StringBuilder sb = new StringBuilder();
String line = "";
BufferedReader bf = new BufferedReader(
new InputStreamReader(in));
while ((line = bf.readLine()) != null) {
sb.append(line);
}
m_response = sb.toString();
}
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return m_response;
}
解析您的回复如下:
String response=getWebserviceResponse("your request Url");
JSONObject jo = new JSONObject(response);
JSONArray resultarr = jo.getJSONArray("msg");
for (int i = 0; i < resultarr.length(); i++)
{
JSONObject jObjresult = resultarr.getJSONObject(i);
String index = jObjresult .getString("index");
String userId=jObjresult .getString("uid"));
JSONArray jObj = jObjresult.getJSONArray("msg");
for (int j = 0; j < jObj.length(); j++)
{
//Get the messages only from the Sender C.
String sender=jObj.getString("sender");
if(sender.equalsIgnoreCase("C")
{
String message = jObj.getString("message");
}
}
}