任何人都可以告诉我为什么在执行json解析后没有得到数据的字符串格式值 ps:连接部分一切正常,现在我只想将json解析方法添加到其中。
try {
strUrl = "http://10.0.2.2/android/login.php?username=" + u + "&password=" + p + "";
URL url = new URL(strUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.connect();
BufferedReader bf = new BufferedReader(new InputStreamReader(con.getInputStream()));
String value = bf.readLine();
String json = value;
JSONObject parentObject = new JSONObject(json);
JSONArray parentArray = parentObject.getJSONArray("Data");
JSONObject finalObject = parentArray.getJSONObject(0);
String username = finalObject.getString("user_name");
String result = username;
return result;
这是我的api结果:
{
"Status": "true",
"Message": "login successfully",
"Data": [{
"user_name": "JS"
}]
}
答案 0 :(得分:0)
试试这个
BufferedReader r = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder total = new StringBuilder();
String value;
while ((value= r.readLine()) != null) {
total.append(value).append('\n');
}
String json = value;
JSONObject parentObject = new JSONObject(json);
JSONArray parentArray = parentObject.getJSONArray("Data");
JSONObject finalObject = parentArray.getJSONObject(0);
String username = finalObject.getString("user_name");
String result = username;
答案 1 :(得分:0)
试试这个。
BufferedReader bf = new BufferedReader(new InputStreamReader(con.getInputStream()));
response = convertStreamToString(in);
JSONObject jObject = new JSONObject(response);
JSONArray jsonMainArr = jObject.getJSONArray("Data");
JSONObject jsonObj = jsonMainArr.getJSONObject(0);
String username = jsonObj.getString("user_name").toString();
return username;
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}