如何在Android Studio中显示JSON的特定数据

huangapple go评论76阅读模式
英文:

How to display specific data of JSON in andorid studio

问题

以下是翻译好的内容:

我是一个初学者,正在尝试创建一个应用程序,根据用户的观影列表和类型偏好显示最新的电影发布信息。我正在使用 OMdb(http://www.omdbapi.com/)API:http://www.omdbapi.com/?apikey=[yourkey]&
JSON 数据仅包含一部电影的数据,而不是数百部电影(可以有人告诉我为什么吗),我只想提取电影的标题。

另外,如果有人知道更好的免费 API,请告诉我。

以下是您提供的 Java 代码:

public class fetchdata extends AsyncTask<Void,Void,Void>{
    String data;
    @Override
    protected Void doInBackground(Void... voids) {
        try {
            URL url = new URL("http://www.omdbapi.com/?i=tt3896198&apikey=e70eecd3");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            InputStream inputstream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputstream));
            String line = "";
            while(line != null){
                line = bufferedReader.readLine();
                data = data + line;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);

        MainActivity.txt.setText(this.data);
    }
}

JSON 数据:

{
  "Title": "银河护卫队2",
  "Year": "2017",
  "Rated": "PG-13",
  "Released": "2017年5月5日",
  "Runtime": "136 分钟",
  "Genre": "动作,冒险,喜剧,科幻",
  "Director": "詹姆斯·古恩",
  "Writer": "詹姆斯·古恩,丹·阿布尼特(基于漫威漫画),安迪·兰宁(基于漫威漫画),史蒂夫·恩格尔哈特(星爵由之创作),史蒂夫·甘(星爵由之创作),吉姆·斯塔林(卡莫拉和德拉克斯由之创作),斯坦·李(格鲁特由之创作),拉里·利伯(格鲁特由之创作),杰克·柯比(格鲁特由之创作),比尔·曼特洛(火箭浣熊由之创作),基思·吉芬(火箭浣熊由之创作),史蒂夫·杰伯(霍华德·大鸭由之创作),瓦尔·梅耶里克(霍华德·大鸭由之创作)",
  "Actors": "克里斯·普拉特,佐伊·索尔达娜,戴夫·巴蒂斯塔,范·迪塞尔",
  "Plot": "银河护卫队在应对个人家庭问题(尤其是星爵与雄心勃勃的天体存在艾戈相遇)的同时努力保持团队的完整性。",
  "Language": "英语",
  "Country": "美国",
  "Awards": "提名获得1项奥斯卡奖。另有15项胜利和56项提名。",
  "Poster": "https://m.media-amazon.com/images/M/MV5BNjM0NTc0NzItM2FlYS00YzEwLWE0YmUtNTA2ZWIzODc2OTgxXkEyXkFqcGdeQXVyNTgwNzIyNzg@._V1_SX300.jpg",
  "Ratings": [
    {
      "Source": "互联网电影数据库",
      "Value": "7.6/10"
    },
    {
      "Source": "烂番茄",
      "Value": "85%"
    },
    {
      "Source": "Metacritic",
      "Value": "67/100"
    }
  ],
  "Metascore": "67",
  "imdbRating": "7.6",
  "imdbVotes": "548,890",
  "imdbID": "tt3896198",
  "Type": "电影",
  "DVD": "2017822日",
  "BoxOffice": "$389,804,217",
  "Production": "华特·迪士尼影片公司",
  "Website": "无",
  "Response": "True"
}
英文:

I am a beginner in app development and trying to create an app to show latest movie releases based on user's watchlist and genre interest. I am using the OMdb (http://www.omdbapi.com/)
api: http://www.omdbapi.com/?apikey=[yourkey]&
The json has data for only one movie instead of hundreds(can somebody plz tell me why) and I just want to extract the title of the movie.

Also if anybody knows a better free api please let me know.

public class fetchdata extends AsyncTask<Void,Void,Void>{
    String data;
    @Override
    protected Void doInBackground(Void... voids) {
        try {
            URL url = new URL("http://www.omdbapi.com/?i=tt3896198&apikey=e70eecd3");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            InputStream inputstream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputstream));
            String line = "";
            while(line != null){
                line = bufferedReader.readLine();
                data = data + line;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);

        MainActivity.txt.setText(this.data);
    }
}

JSON data

{
  "Title": "Guardians of the Galaxy Vol. 2",
  "Year": "2017",
  "Rated": "PG-13",
  "Released": "05 May 2017",
  "Runtime": "136 min",
  "Genre": "Action, Adventure, Comedy, Sci-Fi",
  "Director": "James Gunn",
  "Writer": "James Gunn, Dan Abnett (based on the Marvel comics by), Andy Lanning (based on the Marvel comics by), Steve Englehart (Star-Lord created by), Steve Gan (Star-Lord created by), Jim Starlin (Gamora and Drax created by), Stan Lee (Groot created by), Larry Lieber (Groot created by), Jack Kirby (Groot created by), Bill Mantlo (Rocket Raccoon created by), Keith Giffen (Rocket Raccoon created by), Steve Gerber (Howard the Duck created by), Val Mayerik (Howard the Duck created by)",
  "Actors": "Chris Pratt, Zoe Saldana, Dave Bautista, Vin Diesel",
  "Plot": "The Guardians struggle to keep together as a team while dealing with their personal family issues, notably Star-Lord's encounter with his father the ambitious celestial being Ego.",
  "Language": "English",
  "Country": "USA",
  "Awards": "Nominated for 1 Oscar. Another 15 wins & 56 nominations.",
  "Poster": "https://m.media-amazon.com/images/M/MV5BNjM0NTc0NzItM2FlYS00YzEwLWE0YmUtNTA2ZWIzODc2OTgxXkEyXkFqcGdeQXVyNTgwNzIyNzg@._V1_SX300.jpg",
  "Ratings": [
    {
      "Source": "Internet Movie Database",
      "Value": "7.6/10"
    },
    {
      "Source": "Rotten Tomatoes",
      "Value": "85%"
    },
    {
      "Source": "Metacritic",
      "Value": "67/100"
    }
  ],
  "Metascore": "67",
  "imdbRating": "7.6",
  "imdbVotes": "548,890",
  "imdbID": "tt3896198",
  "Type": "movie",
  "DVD": "22 Aug 2017",
  "BoxOffice": "$389,804,217",
  "Production": "Walt Disney Pictures",
  "Website": "N/A",
  "Response": "True"
}

答案1

得分: 0

可以使用Gson来解析JSON,并且可以在以下链接中找到免费的API:https://github.com/public-apis/public-apis。

英文:

You can use Gson to bark Jason
and
https://github.com/public-apis/public-apis
Link api free

答案2

得分: 0

尽管我不确定您想如何处理这些数据,希望得到多少个响应,或者对这个特定应用有哪些其他限制,但以下是一种快速提取特定电影标题的方法。

基本方法:

首先,如果您使用AndroidStudio的一些JSON对象(位于org.json包内),可能会更容易管理数据。

假设我们使用以下来自OMDb API的响应:

{"Title":"Blade Runner","Year":"1982","Rated":"R","Released":"25 Jun 1982","Runtime":"117 min","Genre":"Action, Sci-Fi, Thriller","Director":"Ridley Scott","Writer":"Hampton Fancher (screenplay), David Webb Peoples (screenplay), Philip K. Dick (novel)","Actors":"Harrison Ford, Rutger Hauer, Sean Young, Edward James Olmos","Plot":"A blade runner must pursue and terminate four replicants who stole a ship in space, and have returned to Earth to find their creator.","Language":"English, German, Cantonese, Japanese, Hungarian, Arabic","Country":"USA","Awards":"Nominated for 2 Oscars. Another 12 wins & 16 nominations.","Poster":"https://m.media-amazon.com/images/M/MV5BNzQzMzJhZTEtOWM4NS00MTdhLTg0YjgtMjM4MDRkZjUwZDBlXkEyXkFqcGdeQXVyNjU0OTQ0OTY@._V1_SX300.jpg","Ratings":[{"Source":"Internet Movie Database","Value":"8.1/10"},{"Source":"Rotten Tomatoes","Value":"90%"},{"Source":"Metacritic","Value":"84/100"}],"Metascore":"84","imdbRating":"8.1","imdbVotes":"679,274","imdbID":"tt0083658","Type":"movie","DVD":"N/A","BoxOffice":"N/A","Production":"Blade Runner Partnership, Ladd Company","Website":"N/A","Response":"True"}

如果我们将这个JSON响应存储在变量data中,我们可以创建一个JSONObject,从中更轻松地提取所需的数据:

JSONObject jsonObject = new JSONObject(data); // 将JSON数据映射到新的JSONObject
String title = jsonObject.getString("Title"); // 字符串'title'将保存值"Blade Runner"

使用JSONObjects,您可以从返回的数据中提取任意数量的键值对。只需确保您了解如何处理不同的数据类型,如果这是您以后开发中需要做的事情(例如,对于整数值,使用jsonElement.getInt("IntegerKey"),对于在响应中有嵌套的JSONObjects,使用jsonElement.getJSONObject("ObjectName")等)。

多对象响应的方法:

如果您期望从响应中返回多个JSON对象(且响应是数组),最好运行一个单独的方法来进行所有数据处理,或者至少在一个更明确的循环结构中处理它们:

JSONArray jsonArray = new JSONArray(data);
JSONObject jsonElement;
String title, year;
// 通过for循环可以遍历返回的'data'字符串中的所有JSON对象
for (int i=0; i < jsonArray.length(); i++) {
jsonElement = jsonArray.getJSONObject(i);
title = jsonElement.getString("Title");
year = jsonElement.getString("Year");
}
// 处理完成后,您可以将其存储在某个数据结构中或将其传递给应用程序的另一部分

基本上,我始终认为AndroidStudio的JSONObjects特别有用。请告诉我这是否有所帮助,或者它对您有何作用!

英文:

Although I'm unsure of what you'd like to do with this data, how many responses you're hoping for, or any other constraints on this particular application - here's a quick method of how you could go about extracting the title for a particular film.

<h2>Basic Approach:</h2>

Firstly, the data might be easiest to manage if you use some of AndroidStudio's JSON objects (located inside the org.json package).

Let's use this response hypothetically (taken from the OMDb API):

{&quot;Title&quot;:&quot;Blade Runner&quot;,&quot;Year&quot;:&quot;1982&quot;,&quot;Rated&quot;:&quot;R&quot;,&quot;Released&quot;:&quot;25 Jun 1982&quot;,&quot;Runtime&quot;:&quot;117 min&quot;,&quot;Genre&quot;:&quot;Action, Sci-Fi, Thriller&quot;,&quot;Director&quot;:&quot;Ridley Scott&quot;,&quot;Writer&quot;:&quot;Hampton Fancher (screenplay), David Webb Peoples (screenplay), Philip K. Dick (novel)&quot;,&quot;Actors&quot;:&quot;Harrison Ford, Rutger Hauer, Sean Young, Edward James Olmos&quot;,&quot;Plot&quot;:&quot;A blade runner must pursue and terminate four replicants who stole a ship in space, and have returned to Earth to find their creator.&quot;,&quot;Language&quot;:&quot;English, German, Cantonese, Japanese, Hungarian, Arabic&quot;,&quot;Country&quot;:&quot;USA&quot;,&quot;Awards&quot;:&quot;Nominated for 2 Oscars. Another 12 wins &amp; 16 nominations.&quot;,&quot;Poster&quot;:&quot;https://m.media-amazon.com/images/M/MV5BNzQzMzJhZTEtOWM4NS00MTdhLTg0YjgtMjM4MDRkZjUwZDBlXkEyXkFqcGdeQXVyNjU0OTQ0OTY@._V1_SX300.jpg&quot;,&quot;Ratings&quot;:[{&quot;Source&quot;:&quot;Internet Movie Database&quot;,&quot;Value&quot;:&quot;8.1/10&quot;},{&quot;Source&quot;:&quot;Rotten Tomatoes&quot;,&quot;Value&quot;:&quot;90%&quot;},{&quot;Source&quot;:&quot;Metacritic&quot;,&quot;Value&quot;:&quot;84/100&quot;}],&quot;Metascore&quot;:&quot;84&quot;,&quot;imdbRating&quot;:&quot;8.1&quot;,&quot;imdbVotes&quot;:&quot;679,274&quot;,&quot;imdbID&quot;:&quot;tt0083658&quot;,&quot;Type&quot;:&quot;movie&quot;,&quot;DVD&quot;:&quot;N/A&quot;,&quot;BoxOffice&quot;:&quot;N/A&quot;,&quot;Production&quot;:&quot;Blade Runner Partnership, Ladd Company&quot;,&quot;Website&quot;:&quot;N/A&quot;,&quot;Response&quot;:&quot;True&quot;}

If we have this JSON response stored in the variable data, we can create a JSONObject - making it much easier to extract the data we want:

JSONObject jsonObject = new JSONObject(data) // maps JSON data to new JSONObject
String title = jsonObject.getString(&quot;Title&quot;); // the string &#39;title&#39; would hold the value &quot;Blade Runner&quot;

Using the JSONObjects you could extract any number of key value pairs from the returned data. Just ensure that you're aware of handling different data types if that's something you'll need to do later in your development (ex: jsonElement.getInt(&quot;IntegerKey&quot;) for integer values, jsonElement.getJSONObject(&quot;ObjectName&quot;) if you have nested JSONObjects within your response, etc.).

<h2>Approach for multi-object responses:</h2>

If you're expecting to return multiple JSON Objects from a response (and the response is an array), it may be better to run a separate method to do all your data processing - or at least process them in a more defined loop structure:

JSONArray jsonArray = new JSONArray(data);
JSONObject jsonElement;
String title, year;
// a for loop can iterate through all json objects within the returned &#39;data&#39; string
for (int i=0; i &lt; jsonArray.length(); i++) {
jsonElement = jsonArray.getJSONObject(i);
title = jsonElement.getString(&quot;Title&quot;);
year = jsonElement.getString(&quot;Year&quot;);
}
// after this is processed you could store it in some data structure or pass it to another part of the application

Essentially, I've always found the AndroidStudio JSONObjects to be particularly useful. Please let me know if that helps at all or how it ends up working for you!

答案3

得分: 0

你必须将数据从字符串转换为 JSON,就像这样:

JsonObject jsonResponse = new JsonObject(this.data);

然后你可以从中获取 title 属性:

MainActivity.txt.setText(jsonResponse.getString("Title"));
英文:

you have to convert the data from stirng to json like these

 JsonObject jsonResponse= new JsonObject(this.data);

and then you can get the title Property from it

MainActivity.txt.setText(jsonResponse.getString(&quot;Title&quot;));

huangapple
  • 本文由 发表于 2020年9月22日 16:17:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/64005674.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定