[英]Json parsing return null value
在我的Android應用程序中,我正在使用json解析登錄。json解析網址包含瀏覽器上的json數據,如下所示
{
posts: [{
status: 1,
user_id: 10,
access_token: "BRBL4JJXB9",
image: "images/users/.PNG",
msg: "Login Successful."
}]
}
但是當調用相同的URL進行JSON解析時,它返回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();
}
變量“ json”返回null。請幫助我找到解決方案。此處r.readLine()為null
您的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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.