You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:基于Oxford Dictionary API的Android词典APP如何提取单词释义

Hey there! Let's fix this together. The issue you're facing—getting the full raw JSON response instead of just the word's definitions—is super common when working with external APIs. Here's a step-by-step guide to extract only the释义 (definitions) from the Oxford Dictionary API response:

Step 1: Understand the Oxford API JSON Structure

First, you need to know how the API's response is structured. A typical response looks like this (simplified):

{
"results": [
{
"lexicalEntries": [
{
"entries": [
{
"senses": [
{
"definitions": ["The definition you want to extract"]
}
]
}
]
}
]
}
]
}
Definitions are nested inside results → lexicalEntries → entries → senses arrays, so we'll need to drill down through these layers.

Step 2: Parse the JSON to Extract Definitions

You have two solid options here: using Android's native JSONObject (no extra libraries) or using Gson for cleaner, object-oriented parsing.

Option 1: Native JSONObject Parsing

Modify your AsyncTask to parse the JSON string and extract only definitions after fetching the response:

private class FetchDefinitionTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... params) {
        String targetWord = params[0];
        String apiUrl = "YOUR_OXFORD_API_ENDPOINT?word=" + targetWord; // Replace with your actual API URL
        
        // Your existing network request code here to get jsonResponse
        String jsonResponse = /* Result from your HTTP request */;
        
        try {
            JSONObject rootObject = new JSONObject(jsonResponse);
            JSONArray resultsArray = rootObject.getJSONArray("results");
            
            // Grab the first result (most words only have one primary entry)
            JSONObject firstResult = resultsArray.getJSONObject(0);
            JSONArray lexicalEntries = firstResult.getJSONArray("lexicalEntries");
            JSONObject firstLexEntry = lexicalEntries.getJSONObject(0);
            JSONArray entries = firstLexEntry.getJSONArray("entries");
            JSONObject firstEntry = entries.getJSONObject(0);
            JSONArray senses = firstEntry.getJSONArray("senses");
            
            // Collect all definitions into a readable format
            StringBuilder definitionsBuilder = new StringBuilder();
            for (int i = 0; i < senses.length(); i++) {
                JSONObject sense = senses.getJSONObject(i);
                JSONArray defs = sense.getJSONArray("definitions");
                // Take the first definition for each sense (adjust if you want multiple)
                String definition = defs.getString(0);
                definitionsBuilder.append("- ").append(definition).append("\n");
            }
            
            return definitionsBuilder.toString().trim();
        } catch (JSONException e) {
            Log.e("DictionaryApp", "JSON parsing failed", e);
            return "Failed to load definition.";
        }
    }

    @Override
    protected void onPostExecute(String definitions) {
        // Update your TextView with the extracted definitions
        TextView definitionView = findViewById(R.id.your_definition_textview_id);
        definitionView.setText(definitions);
    }
}

Option 2: Gson (Cleaner, Object-Oriented Parsing)

If you want to avoid nested JSON checks, use Google's Gson library to map the JSON response directly to Java objects.

  1. First, add the Gson dependency to your module-level build.gradle:
dependencies {
    implementation 'com.google.code.gson:gson:2.10.1'
}
  1. Create model classes that mirror the API's JSON structure:
public class OxfordDictionaryResponse {
    public List<Result> results;

    public static class Result {
        public List<LexicalEntry> lexicalEntries;
    }

    public static class LexicalEntry {
        public List<Entry> entries;
    }

    public static class Entry {
        public List<Sense> senses;
    }

    public static class Sense {
        public List<String> definitions;
    }
}
  1. Update your AsyncTask to use Gson for parsing:
private class FetchDefinitionTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... params) {
        String targetWord = params[0];
        String apiUrl = "YOUR_OXFORD_API_ENDPOINT?word=" + targetWord;
        
        String jsonResponse = /* Result from your HTTP request */;
        
        try {
            Gson gson = new Gson();
            OxfordDictionaryResponse response = gson.fromJson(jsonResponse, OxfordDictionaryResponse.class);
            
            StringBuilder definitionsBuilder = new StringBuilder();
            // Safely traverse the nested objects/arrays to avoid nulls
            if (response != null && response.results != null && !response.results.isEmpty()) {
                Result firstResult = response.results.get(0);
                if (firstResult.lexicalEntries != null && !firstResult.lexicalEntries.isEmpty()) {
                    LexicalEntry firstLexEntry = firstResult.lexicalEntries.get(0);
                    if (firstLexEntry.entries != null && !firstLexEntry.entries.isEmpty()) {
                        Entry firstEntry = firstLexEntry.entries.get(0);
                        if (firstEntry.senses != null && !firstEntry.senses.isEmpty()) {
                            for (Sense sense : firstEntry.senses) {
                                if (sense.definitions != null && !sense.definitions.isEmpty()) {
                                    definitionsBuilder.append("- ").append(sense.definitions.get(0)).append("\n");
                                }
                            }
                        }
                    }
                }
            }
            
            return definitionsBuilder.length() > 0 ? definitionsBuilder.toString().trim() : "No definition found.";
        } catch (Exception e) {
            Log.e("DictionaryApp", "Error parsing definition", e);
            return "Failed to load definition.";
        }
    }

    @Override
    protected void onPostExecute(String definitions) {
        TextView definitionView = findViewById(R.id.your_definition_textview_id);
        definitionView.setText(definitions);
    }
}
Step 3: Handle Edge Cases
  • Always check if arrays/objects are null or empty before accessing them to avoid crashes (NullPointerException or IndexOutOfBoundsException).
  • Some words have multiple lexical entries (e.g., different parts of speech like noun/verb)—you can adjust the code to show all entries or let users select which one to view.
  • Add error handling for network failures, invalid API keys, or words that don't exist in the dictionary.

内容的提问来源于stack exchange,提问作者Flavy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:27:07