我目前正在开发一个应用程序,需要从未命名数组中解析 JSON 对象。
我只能设法解析名称如下的 JSON 数组:http://jsonparsing.parseapp.com/jsonData/moviesDemoItem.txt .
我用于上面代码的代码是
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String asd = buffer.toString();
JSONObject parentObject = new JSONObject(asd);
JSONArray parentArray = parentObject.getJSONArray("movies");
JSONObject fObject = parentArray.getJSONObject(0);
String movie = fObject.getString("movie");
int year = fObject.getInt("year");
return movie + year;
代码包含“movies”,它是数组名称。
我应该更改什么才能仅解析 JSON 数组中的对象,例如 https://restcountries.eu/rest/v1/all ?
最佳答案
您的国家/地区列表只是一个数组。不需要名字。
简单地替换
JSONObject parentObject = new JSONObject(asd);
与
JSONArray parentObject = new JSONArray(asd);
请参阅这篇文章,了解如何迭代该数组以解析其余对象。
开始类似的事情
for (int i=0; i < parentObject.length(); i++) {
或者,Volley 的 JsonArrayRequest
会很有用,或者如果您不想自己手动解析 JSON 数据,那么了解 Retrofit+Gson 会更好。
关于java - 从 JSON 数组解析 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40309694/