在我的android应用程序中,我使用登录json parsing.Json解析url包含浏览器上的json数据,如下所示
{
posts: [{
status: 1,
user_id: 10,
access_token: "BRBL4JJXB9",
image: "images/users/.PNG",
msg: "Login Successful."
}]
}
但是在为JSON解析调用相同的URL时,它返回null。我解析下面的代码
@Override
protected Void doInBackground(Void... params) {
String url = "";
url = URLS.BASEURL + "mobile_api.php?action=userLogin&user_name=" +plusname+"&image="+plusimage+"&email="+URLEncoder.encode(gmail) +"&gcm_id="+deviceid;
JSONReader reader = new JSONReader();
json = getJsonGET(url);
if (json != null) {
try {
JSONObject response = new JSONObject(json);
JSONArray arr = response.getJSONArray("posts");
for (int index = 0; index < arr.length(); index++) {
JSONObject jobj = arr.getJSONObject(index);
status = jobj.getString("status");
if (status.equalsIgnoreCase("1")) {
userid = jobj.getString("user_id");
accesstoken = jobj.getString("access_token");
SharedPreferences.Editor edit = m_pref.edit();
edit.putString("userid", userid);
edit.putString("accesstoken", accesstoken);
edit.commit();
} else {
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
private String getJsonGET(String url) {
String contentAsString;
StringBuilder total = new StringBuilder();
try {
InputStream is = null;
try {
URL url2 = new URL(url);
HttpURLConnection conn = (HttpURLConnection) url2.openConnection();
conn.setReadTimeout(100000 /* milliseconds */);
conn.setConnectTimeout(150000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
int response = conn.getResponseCode();
Log.d("", "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
Reader reader = null;
reader = new InputStreamReader(is, "UTF-8");
BufferedReader r = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
char[] buffer = new char[total.length()];
reader.read(buffer);
contentAsString = new String(buffer);
} finally {
if (is != null) {
is.close();
}
}
} catch (Exception e) {
return null;
}
return total.toString();
}
变量&#34; json&#34; return null。请帮我找到解决方案。这里r.readLine()为null
答案 0 :(得分:0)
你的json输出应该是..
{"posts": [{"status": 1,"user_id": 10,"access_token": "BRBL4JJXB9","image": "images/users/.PNG","msg": "Login Successful."}]}
第二个是你将status
和user_id
解析为string
,但它是int
所以你的语法和条件应该是......
int status = jsonObject.getInt("status");
if (status == 1)) {
int userid = jobj.getInt("user_id");
String accesstoken = jobj.getString("access_token");
SharedPreferences.Editor edit = m_pref.edit();
edit.putInt("userid", userid);
edit.putString("accesstoken", accesstoken);
edit.commit();
}