简体   繁体   English

从JSON数组解析JSON对象

[英]Parsing JSON Object from a JSON array

I am currently developing an app and need to parse JSON objects from inside an unnamed array. 我目前正在开发一个应用,需要从一个未命名的数组中解析JSON对象。
I can only manage to parse JSON arrays with a name such as this one: http://jsonparsing.parseapp.com/jsonData/moviesDemoItem.txt . 我只能使用以下名称来解析JSON数组: http : //jsonparsing.parseapp.com/jsonData/moviesDemoItem.txt

The code that I used for the one above is 我用于以上代码的代码是

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;

The code includes "movies" which is the array name . 该代码包括数组数组名称“ movies”。
What should I change to parse only the objects from within a JSON array such as https://restcountries.eu/rest/v1/all ? 我应该更改什么以仅解析JSON数组(例如https://restcountries.eu/rest/v1/all)中的对象

Your countries list is simply an array. 您的国家/地区列表只是一个数组。 Doesn't need a name. 不需要名字。

Simply replace 只需更换

JSONObject parentObject = new JSONObject(asd);

with

JSONArray parentObject = new JSONArray(asd);

See this post for how to iterate over that array to parse the remainder of the objects. 有关如何遍历该数组以解析其余对象的信息,请参见这篇文章。

How to parse JSON in Android 如何在Android中解析JSON

Starting something like 开始像

for (int i=0; i < parentObject.length(); i++) {

Alternatively, Volley's JsonArrayRequest would be useful, or learning about Retrofit+Gson would be even better if you don't feel like manually parsing the JSON data yourself. 另外,Volley的JsonArrayRequest会很有用,或者如果您不想自己手动解析JSON数据,则对Retrofit + Gson的了解会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM