簡體   English   中英

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

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

我嘗試從 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"
  }
}

但它發生了錯誤。 我試圖將jsonObj.getJSONArray("contents")更改為jsonObj.getJSONArray("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

我怎么只能得到引用和作者?

這是我的編碼。

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是 Object 不是數組記住所有 JSON 數組在開始和結束處都有[]在那里 JSON 表示。

任何以{}開頭的東西都是 JSON 解析器的結構/JSONObject

您的 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM