2016-10-28 180 views
0

我目前正在开发一个应用程序,需要从一个未命名的数组中解析JSON对象。
我只能设法解析JSON数组,名称如下:http://jsonparsing.parseapp.com/jsonData/moviesDemoItem.txt从JSON数组解析JSON对象

高于予用于所述一个代码是

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

+1

您应该最好从'doInBackground'返回'buffer.toString()'或'parentObject'。在'onPostExecute'中执行剩余的JSON解析。 –

+0

[如何在Android中解析JSON]可能的重复(http://stackoverflow.com/questions/9605913/how-to-parse-json-in-android) –

回答

2

你的国家名单只是一个数组。不需要名称。

只需使用

JSONArray parentObject = new JSONArray(asd); 

更换

JSONObject parentObject = new JSONObject(asd); 

看到这个职位对如何在该数组迭代解析的对象的其余部分。

How to parse JSON in Android

开始像

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

另外,排球的JsonArrayRequest将是有益的,或者如果你不喜欢手动解析自己的JSON数据了解改造+ GSON甚至会更好。