gpt4 book ai didi

android - 从 JSON 获取数据?

转载 作者:行者123 更新时间:2023-11-29 14:43:11 26 4
gpt4 key购买 nike

我想从这里获取用户名 Json url .我有这段代码,但它不让我得到数据说

Json parsing error

代码如下:

HttpHandler.java

public class HttpHandler {

private static final String TAG = HttpHandler.class.getSimpleName();

public HttpHandler() {
}

public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}

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();
}
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

private String TAG = MainActivity.class.getSimpleName();

private ProgressDialog pDialog;
private ListView lv;

// URL to get contacts JSON
private static String url = "https://someLink";

ArrayList<HashMap<String, String>> contactList;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

contactList = new ArrayList<>();

lv = (ListView) findViewById(R.id.list);

new GetContacts().execute();
}

/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {

@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();

}

@Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();

// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);

Log.e(TAG, "Response from url: " + jsonStr);

if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);

// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("");

// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);

String name = c.getString("username");

// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();

// adding each child node to HashMap key => value
contact.put("username", name);

// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});

}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});

}

return null;
}

@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"username"}, new int[]{R.id.name});

lv.setAdapter(adapter);
}

}
}

这是我在谷歌上找到的一个例子,并试图根据我的需要稍微改变它。我放了一个空的 JsonArray。我也尝试了其他例子,但我不明白出了什么问题。

**

>新问题

如果我的url是这样的?和其他的有什么区别?

new Json

**

最佳答案

您没有要在输出中解析的数组。您的 URL 为您提供了一个对象。你的代码应该是这样的

    if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String name = jsonObj.getString("username");
//... now use the whereever you want
}
catch (final JSONException e) {
//... put your error log
}

关于android - 从 JSON 获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53042248/

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