【问题标题】:Not able to Parse this JSON Array . with sub arrays and objects无法解析此 JSON 数组。带有子数组和对象
【发布时间】:2018-07-31 19:47:57
【问题描述】:

我要解析的 JSON。 我要解析的两个 JSON 数据。并提供了我的 mainActivty 代码,请看一下。 我已经访问了 JSON 数组并对其进行循环获取第一个元素的对象并尝试从第一个元素中获取详细信息,不幸的是我无法获取它们。我试图记录从 postExecute 返回的 arrayListed。它仍然显示 size =0..

[
 {
"score": 24.910917,
"show": {
  "id": 13,
  "url": "http://www.tvmaze.com/shows/13/the-flash",
  "name": "The Flash",
  "type": "Scripted",
  "language": "English",
  "genres": [
    "Drama",
    "Action",
    "Science-Fiction"
  ],
  "status": "Running",
  "runtime": 60,
  "premiered": "2014-10-07",
  "officialSite": "http://www.cwtv.com/shows/the-flash/",
  "schedule": {
    "time": "20:00",
    "days": [
      "Tuesday"
    ]
  },
  "rating": {
    "average": 8.1
  },
  "weight": 99,
  "network": {
    "id": 5,
    "name": "The CW",
    "country": {
      "name": "United States",
      "code": "US",
      "timezone": "America/New_York"
    }
  },
  "webChannel": null,
  "externals": {
    "tvrage": 36939,
    "thetvdb": 279121,
    "imdb": "tt3107288"
  },
  "image": {
    "medium": "http://static.tvmaze.com/uploads/images/medium_portrait/129/323466.jpg",
    "original": "http://static.tvmaze.com/uploads/images/original_untouched/129/323466.jpg"
  },
  "summary": "<p>After a particle accelerator causes a freak storm, CSI Investigator Barry Allen is struck by lightning and falls into a coma. Months later he awakens with the power of super speed, granting him the ability to move through Central City like an unseen guardian angel. Though initially excited by his newfound powers, Barry is shocked to discover he is not the only \"meta-human\" who was created in the wake of the accelerator explosion -- and not everyone is using their new powers for good. Barry partners with S.T.A.R. Labs and dedicates his life to protect the innocent. For now, only a few close friends and associates know that Barry is literally the fastest man alive, but it won't be long before the world learns what Barry Allen has become...The Flash!</p>",
  "updated": 1532242720,
  "_links": {
    "self": {
      "href": "http://api.tvmaze.com/shows/13"
    },
    "previousepisode": {
      "href": "http://api.tvmaze.com/episodes/1426878"
    },
    "nextepisode": {
      "href": "http://api.tvmaze.com/episodes/1473791"
    }
  }
}
},
{
"score": 22.392826,
"show": {
  "id": 528,
  "url": "http://www.tvmaze.com/shows/528/the-flash",
  "name": "The Flash",
  "type": "Scripted",
  "language": "English",
  "genres": [
    "Action",
    "Adventure",
    "Science-Fiction"
  ],
  "status": "Ended",
  "runtime": 60,
  "premiered": "1990-09-20",
  "officialSite": null,
  "schedule": {
    "time": "20:30",
    "days": [

    ]
  },
  "rating": {
    "average": 8.6
  },
  "weight": 71,
  "network": {
    "id": 2,
    "name": "CBS",
    "country": {
      "name": "United States",
      "code": "US",
      "timezone": "America/New_York"
    }
  },
  "webChannel": null,
  "externals": {
    "tvrage": 5781,
    "thetvdb": 78650,
    "imdb": "tt0098798"
  },
  "image": {
    "medium": "http://static.tvmaze.com/uploads/images/medium_portrait/4/11360.jpg",
    "original": "http://static.tvmaze.com/uploads/images/original_untouched/4/11360.jpg"
  },
  "summary": "<p>The Flash is Barry Allen, a police scientist, who was working one night during a terrible thunder storm when a bolt of lightning crashes through the lab window, electrocuting him. Barry survives and soon learns that he is now able to move at almost incomprehensible speed.</p>",
  "updated": 1509496066,
  "_links": {
    "self": {
      "href": "http://api.tvmaze.com/shows/528"
    },
    "previousepisode": {
      "href": "http://api.tvmaze.com/episodes/47947"
    }
  }
}
},

主要活动

 package com.vineet.moviesapp;

 import android.net.Uri;
 import android.os.AsyncTask;
 import android.support.v7.app.AppCompatActivity;
 import android.os.Bundle;
 import android.util.Log;
 import android.view.View;
 import android.widget.Button;
 import android.widget.TextView;

 import org.json.JSONArray;
 import org.json.JSONException;
 import org.json.JSONObject;

 import java.io.IOException;
 import java.io.InputStream;
 import java.net.HttpURLConnection;
 import java.net.MalformedURLException;
 import java.net.URL;
 import java.util.ArrayList;
 import java.util.Scanner;

public class MainActivity extends AppCompatActivity {

private static final String TAG = "LOG MESSAGE";

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

    Button btnGet = findViewById(R.id.btnGet);

    btnGet.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            updateTextView();
        }
    });
}



public void updateTextView(){
    NetworkTask networkTask = new NetworkTask();
    networkTask.execute("https://api.tvmaze.com/search/shows?q=flash");
}

class NetworkTask extends AsyncTask<String, Void, String>{

    @Override
    protected String doInBackground(String... strings) {
        String stringUrl = strings[0];
        try {
            URL url = new URL(stringUrl);
            HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();

            InputStream inputStream = httpURLConnection.getInputStream();

            Scanner scanner = new Scanner(inputStream);
            scanner.useDelimiter("\\A");
            if (scanner.hasNext()){
                String s = scanner.next();
                return s;
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        ArrayList<Movie> movieArrayList = parseJson(s);
        Log.d(TAG,"onPostExec"+ movieArrayList.size());
    }
}

ArrayList<Movie> parseJson(String s){
    ArrayList<Movie> movies = new ArrayList<>();

    try {

        JSONArray root = new JSONArray(s);

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

            JSONObject object = root.getJSONObject(i);

            Integer score = object.getInt("score");
            String name = object.getJSONObject("show").getString("name");
            String language = object.getJSONObject("show").getString("language");
            String image = object.getJSONObject("show").getJSONObject("image").getString("medium");
            Double rating = object.getJSONObject("show").getDouble("average");

            Movie movie = new Movie(score,name,language,image,rating);
            movies.add(movie);
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }

    return movies;
}
}

我尝试过以我的方式解析数据。但无法解析它。请帮助我,让我知道我在哪里犯了错误。

【问题讨论】:

  • 您发布的 json 缺少尾随 ] 而不是逗号。在您的应用程序中也是如此吗?
  • 没有。我刚刚发布了一些来自 api 的对象,为什么你看不到 ]

标签: android json api networking


【解决方案1】:

乍一看可能是这个

    Integer score = object.getInt("score");

因为你的 json 分数是 "score": 24.910917 。这是双重的。
也在这一行

    Double rating = object.getJSONObject("show").getDouble("average");

json 是

"rating": {
    "average": 8.1
  },

应该是这样的

 Double rating = object.getJSONObject("show").getJSONObject("rating").getDouble("average");

【讨论】:

  • 谢谢。我试过了,它现在可以工作但我想再问一个我有 10 个对象的 JSON 数据,但解析后我只得到 4 个对象的数据/?
  • 很可能解析失败并被 try catch 捕获。请发布解析的堆栈跟踪。您可以通过在 e.printStackTrace() 上放置一个断点来进行测试;看看它是否被击中
【解决方案2】:

不想分散 Tomer Shemesh 的回答,但如果您无法控制正在访问的 API,那么我建议您使用 opt 方法来访问 JSON 字符串中的值。 opt 方法提供了在密钥由于某种原因不可用时添加可选值的能力。例如你可以试试这个:

JSONArray root = new JSONArray(s);
for(int i=0; i<root.length(); i++){
    JSONObject object = root.getJSONObject(i);

    Double score = object.optDouble("score", -1);

    JSONObject showObject = object.getJSONObject("show");
    String name = showObject.optString("name", "Name NA");
    String language = showObject.optString("language", "Language NA");

    JSONObject imageObject = showObject.getJSONObject("image");
    String image = imageObject.optString("medium", "Image Medium NA");

    JSONObject ratingObject = showObject.getJSONObject("rating");
    Double rating = ratingObject.optDouble("average", -1);

    Movie movie = new Movie(score,name,language,image,rating);
    movies.add(movie);
}

请注意,例如showObject.optString("name", "Name NA"); 会在键“name”不可用时为您提供一个可选值——如果它不存在,您将获得字符串“Name NA”而不是导致错误。同样,如果键“average”不可用,ratingObject.optDouble("average", -1); 将返回“-1”。

例子:如果你只使用getString("name");' and the "name" key is not present in the JSON string, then you will get an error and the loop will stop. If however, you haveoptString("name", "NA");'并且 JSON 字符串中不存在“name”键,您将得到“NA”并且循环将继续。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-02
    • 1970-01-01
    • 2016-11-20
    • 2013-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多