我目前正在开发一个应用程序,需要从一个未命名的数组中解析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;
代码包含“电影”,即阵列名称 我应该更改什么才能解析JSON数组中的对象,例如https://restcountries.eu/rest/v1/all?
答案 0 :(得分:2)
您的国家/地区列表只是一个数组。不需要名字。
简单地替换
JSONObject parentObject = new JSONObject(asd);
带
JSONArray parentObject = new JSONArray(asd);
有关如何迭代该数组以解析其余对象的信息,请参阅此文章。
开始像
这样的事情for (int i=0; i < parentObject.length(); i++) {
或者,Volley的JsonArrayRequest
会很有用,或者如果您不想亲自手动解析JSON数据,那么了解Retrofit + Gson会更好。