简体   繁体   English

我怎样才能在 JSON 中得到一些值?

[英]How can I get a some value in a JSON?

I try to get a quote and author which inside of contents from the API. As I want to only show the quote and author in android App.我尝试从 API 的内容中获取引用和作者。因为我只想在 android App 中显示引用和作者。

{
  "success": {
    "total": 1
  },
  "contents": {
    "quotes": [
      {
        "quote": "Give me golf clubs, fresh air and a beautiful partner, and you can keep the clubs and the fresh air.",
        "length": "100",
        "author": "Jack Benny",
        "tags": {
          "0": "funny",
          "1": "golf",
          "2": "sports",
          "4": "tod"
        },
        "category": "funny",
        "language": "en",
        "date": "2020-05-17",
        "permalink": "https://theysaidso.com/quote/jack-benny-give-me-golf-clubs-fresh-air-and-a-beautiful-partner-and-you-can-keep",
        "id": "CzZGhQUP5nApJRq5BaqiggeF",
        "background": "https://theysaidso.com/img/qod/qod-funny.jpg",
        "title": "Funny Quote of the day"
      }
    ]
  },
  "baseurl": "https://theysaidso.com",
  "copyright": {
    "year": 2022,
    "url": "https://theysaidso.com"
  }
}

But it error occurred.但它发生了错误。 I tried to change the jsonObj.getJSONArray("contents") to jsonObj.getJSONArray("quotes") .我试图将jsonObj.getJSONArray("contents")更改为jsonObj.getJSONArray("quotes") However,It also have a error that it return no value in quotes.但是,它也有一个错误,即它在引号中不返回任何值。

org.json.JSONException: Value {"quotes":[{"quote":"Give me golf clubs, fresh air and a beautiful partner, and you can keep the clubs and the fresh air.","length":"100","author":"Jack Benny","tags":{"0":"funny","1":"golf","2":"sports","4":"tod"},"category":"funny","language":"en","date":"2020-05-17","permalink":"https:\/\/theysaidso.com\/quote\/jack-benny-give-me-golf-clubs-fresh-air-and-a-beautiful-partner-and-you-can-keep","id":"CzZGhQUP5nApJRq5BaqiggeF","background":"https:\/\/theysaidso.com\/img\/qod\/qod-funny.jpg","title":"Funny Quote of the day"}]} at contents of type org.json.JSONObject cannot be converted to JSONArray

How can I only get the quote and author?我怎么只能得到引用和作者?

Here is my coding.这是我的编码。

public class MainActivity extends AppCompatActivity {

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

        TextViewResult = findViewById(R.id.view);

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url("https://quotes.rest/qod?category=funny&language=en")
                .get()
                .build();



        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
            if(response.isSuccessful()){
                final String MyResponse = response.body().string();

                JSONObject jsonObj = null;
                try {
                    jsonObj = new JSONObject(MyResponse);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                try {
                    assert jsonObj != null;
                    JSONArray contacts = jsonObj.getJSONArray("contents");

                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(1);

                        final String id = c.getString("id");


                        MainActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                TextViewResult.setText(id);
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

//
//                MainActivity.this.runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//
//                        TextViewResult.setText(MyResponse);
//                    } 
//                });
            }else {
                throw new IOException("Unexpected code " + response);
            };
            }
        });

    }
}

contents is an Object not an Array remember all JSON array have [ and ] at start and end in there JSON representation. contents是 Object 不是数组记住所有 JSON 数组在开始和结束处都有[]在那里 JSON 表示。

Any thing that starts with { and } is a struct/JSONObject for JSON parsers任何以{}开头的东西都是 JSON 解析器的结构/JSONObject

Your for loop can fixed as below您的 for 循环可以修复如下

JSONArray contacts = jsonObj.getJSONObject("contents").getJSONArray("quotes"); // fetch quotes as JSON Array
        for (int i = 0; i < contacts.length(); i++) {   // Iterate over quotes
            String quote = contacts.getJSONObject(i).getString("quote");   // Fetch quote from JSON object
            String author = contacts.getJSONObject(i).getString("author"); // Fetch author from JSON object
            System.out.println(" quote=" + quote + " author="+author);
        }

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

相关问题 如何从具有部分字段名称的JSON获取值 - How can I get a value from a JSON with a partially field name 如何通过Java获取响应值(json)到字符串 - how can I get response value (json) to String via Java 使用 JsonPath 如何获得这些 json 对象的内部值 - Using JsonPath how can I get the inner value of these json objects Java:如何从脚本标签获取JSON值? - Java: How can I get JSON value from a script tag? 如何从json中的值获取子字段? - How can I get a subfield from value in json? 如何在Java上使用Selenium WebDriver从json调用(发布,获取,JSON)中获取任何值? - How can i get any value from json calls (Post, Get, JSON) with Selenium WebDriver on Java? 如何使用 org.json 库从 Java 中的 JSON 文件中获取每个键和值? - How can I get every key and value from a JSON file in Java using the org.json library? 使用 Jackson 注释我怎样才能在 output Z0ECD402181C1D7A2D78 中为字段和值获取单独的 JSON 行? - Using Jackson annotations how can I get a separate JSON row for field and value in the output JSON? 如何修改此字符串并从 Java 中的 JSON 对象获取我想要的值? - How can i modify this string and get the value I want from JSON Object in java? 我如何在 android studio 的 Json 解析器中放置一些条件 - How can i put some condition in Json parser in android studio
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM