如何使用Oxford Dictionary api制作字典应用程序?

时间:2017-06-08 07:43:30

标签: java android json api

这是我从文档中获得的代码,我知道,我收到了JSON格式的结果。但我只需要这个词的含义。所以任何人都可以告诉我如何只提取搜索词的含义,而不是获取整个JSON文件。我是android开发的新手,请帮帮我。

package com.example.hsekar.dictionarytestbeta;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    new CallbackTask().execute(dictionaryEntries());
}

private String dictionaryEntries() {
    final String language = "en";
    final String word = "Ace";
    final String word_id = word.toLowerCase(); //word id is case sensitive and lowercase is required
    return "https://od-api.oxforddictionaries.com:443/api/v1/entries/" + language + "/" + word_id;
}


//in android calling network requests on the main thread forbidden by default
//create class to do async job
private class CallbackTask extends AsyncTask<String, Integer, String> {

    @Override
    protected String doInBackground(String... params) {

        //TODO: replace with your own app id and app key
        final String app_id = "10742428";
        final String app_key = "ada344f3a7a7c7de0315fb78c5c9d6f9";
        try {
            URL url = new URL(params[0]);
            HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
            urlConnection.setRequestProperty("Accept","application/json");
            urlConnection.setRequestProperty("app_id",app_id);
            urlConnection.setRequestProperty("app_key",app_key);

            // read the output from the server
            BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            StringBuilder stringBuilder = new StringBuilder();

            String line = null;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line + "\n");
            }

            return stringBuilder.toString();

        }
        catch (Exception e) {
            e.printStackTrace();
            return e.toString();
        }
    }

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

        Log.d("This will be my result",result);
    }
  }
 }

以下是我的输出。我只是在Logcat中打印它,但是一旦我得到了这个概念,我就会开始研究这个项目。

This will be my result: {
                          "metadata": {
                              "provider": "Oxford University Press"
                          },
                          "results": [
                              {
                                  "id": "ace",
                                  "language": "en",
                                  "lexicalEntries": [
                                      {
                                          "entries": [
                                              {
                                                  "etymologies": [
                                                      "Middle English (denoting the ‘one’ on dice): via Old French from Latin as ‘unity, a unit’"
                                                  ],
                                                  "grammaticalFeatures": [
                                                      {
                                                          "text": "Singular",
                                                          "type": "Number"
                                                      }
                                                  ],
                                                  "homographNumber": "000",
                                                  "senses": [
                                                      {
                                                          "definitions": [
                                                              "a playing card with a single spot on it, ranked as the highest card in its suit in most card games"
                                                          ],
                                                          "domains": [
                                                              "Cards"
                                                          ],
                                                          "examples": [
                                                              {
                                                                  "registers": [
                                                                      "figurative"
                                                                  ],
                                                                  "text": "life had started dealing him aces again"
                                                              },
                                                              {
                                                                  "text": "the ace of diamonds"
                                                              }
                                                          ],
                                                          "id": "m_en_gbus0005680.006"
                                                      },
                                                      {
                                                          "definitions": [
                                                              "a person who excels at a particular sport or other activity"
                                                          ],
                                                          "domains": [
                                                              "Sport"
                                                          ],
                                                          "examples": [
                                                              {
                                                                  "text": "a motorcycle ace"
                                                              }
                                                          ],
                                                          "id": "m_en_gbus0005680.010",
                                                          "registers": [
                                                              "informal"
                                                          ],
                                                          "subsenses": [
                                                              {
                                                                  "definitions": [
                                                                      "a pilot who has shot down many enemy aircraft"
                                                                  ],
                                                                  "domains": [
                                                                      "Air Force"
                                                                  ],
                                                                  "examples": [
                                                                      {
                                                                          "text": "a Battle of Britain ace"
                                                                      }
                                                                  ],
                                                                  "id": "m_en_gbus0005680.011"
                                                              }
                                                          ]
                                                      },
                                                      {
                                                          "definitions": [
                                                              "(in tennis and similar games) a service that an opponent is unable to return and thus wins a point"
                                                          ],
                                                          "domains": [
                                                              "Tennis"

所以我的问题是如何从这个输出中仅提取'含义'部分?

2 个答案:

答案 0 :(得分:0)

你提到的Json结果是不完整的。结果中的对象没有关闭。这就是你从json字符串得到结果的方式。

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    try {
       JSONObject js = new JSONObject(result);
        JSONArray results = js.getJSONArray("results");
        for(int i = 0;i<results.length();i++){
            JSONObject lentries = results.getJSONObject(i);
            JSONArray la = lentries.getJSONArray("lexicalEntries");
            for(int j=0;j<la.length();j++){
                JSONObject entries = la.getJSONObject(j);
                JSONArray e = entries.getJSONArray("entries");
                for(int i1=0;i1<e.length();i1++){
                    JSONObject senses = la.getJSONObject(i1);
                    JSONArray s = entries.getJSONArray("senses");
                    JSONObject d = s.getJSONObject(0);
                    JSONArray de = d.getJSONArray("definitions");
                    def = de.getString(0);
                }
            }
        }
        Log.e("def",def);

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

答案 1 :(得分:-1)

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        //Log.d("This will be my result",result);


        String def = "";
        try {
            JSONObject js = new JSONObject(result);
            JSONArray results = js.getJSONArray("results");
            for (int i = 0; i < results.length(); i++) {
                JSONObject lentries = results.getJSONObject(i);
                JSONArray la = lentries.getJSONArray("lexicalEntries");
                for (int j = 0; j < la.length(); j++) {
                    JSONObject entries = la.getJSONObject(j);
                    JSONArray e = entries.getJSONArray("entries");
                    for (int k= 0; k < e.length(); k++) {
                        JSONObject senses = e.getJSONObject(k);
                        JSONArray s = senses.getJSONArray("senses");
                        JSONObject d = s.getJSONObject(0);
                        JSONArray de = d.getJSONArray("definitions");
                        def = de.getString(0);
                    }
                }
            }
            Log.e("def", def);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //Log.d("This will be my result",result);
    }