gpt4 book ai didi

android - Json 数组在 Android 中解析时返回 null

转载 作者:行者123 更新时间:2023-11-30 03:37:09 25 4
gpt4 key购买 nike

我知道这是一个非常常见的问题,我在 SO 中发现了很多帖子。我的代码如下,我没有看到 json 数组返回 null 的原因。有人可以帮我复习一下吗?我想尽一切办法! :(

JsonArray jsonArr = JSONfunctions.getJSONfromURL(url);
try {
if (jsonArr != null) {
for (int i = 0; i < jsonArr.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonObj = jsonArr.getJSONObject(i);

map.put(TAG_CODE, jsonObj.getString("Code"));
map.put(TAG_DISPLAY_NAME, jsonObj.getString("UserName"));
map.put(TAG_PROGRAM_NAME, jsonObj.getString("Password"));
mylist.add(map);
}
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}






public class JSONfunctions {

public static JSONArray getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONArray jArray = null;

// http post
try {

HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet(url);
// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();

} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}

// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();

// Result is always returning me an array.(not null)

} catch (Exception e) {
Log.e("log_tag", "Error converting result " + result);
}
try {
jArray = new JSONArray(result);

// Goes into the catch block

} catch (JSONException e) {
// TODO Auto-generated catch block
Log.e("log_tag", "Error parsing result " + result);
}
return jArray;

}

最佳答案

服务器返回的内容({"FirstName": "\"firstname"", "LastName": "\"lastname\"", "Code": "\"id\"") ) 是一个 JSONObject 而不是 JSONArray,你应该改变

JSONArray jArray = null;

JSONOBject jArray = null;

jArray = new JSONArray(result);

jArray = new JSONOBject (result);

关于android - Json 数组在 Android 中解析时返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16496767/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com