如何从JSON对象生成一个String?

时间:2016-07-19 21:07:55

标签: java json string

我试图获得"定义"字符串超出以下JSON代码段:

{
      "headword": "Google",
      "senses": [
        {
          "definition": [
            "a very popular search enginecomputer program that allows you to search for information on the Internet. Google also provides other Internet services including e-mail, maps, social networking, and video sharing."
          ]
        }
      ],
      "datasets": [
        "ldoce5",
        "dictionary"
      ],
      "id": "cqAFJKTgNJ",
      "url": "/v2/dictionaries/entries/cqAFJKTgNJ",
      "pronunciations": [
        {
          "audio": [
            {
              "lang": "British English",
              "type": "pronunciation",
              "url": "/v2/dictionaries/assets/ldoce/gb_pron/google1004.mp3"
            },
            {
              "lang": "American English",
              "type": "pronunciation",
              "url": "/v2/dictionaries/assets/ldoce/us_pron/google1004a.mp3"
            }
          ],
          "ipa": "ˈɡuːɡəl"
        }
      ]
    }

问题在于当前的JSON片段"定义"似乎是一个JSONObject,每当我尝试使它成为String时,我得到一个错误,说它不是一个字符串。当我按原样保留对象时,输出包括括号和其他符号:

{"definition":["a very popular search enginecomputer program that allows you to search for information on the Internet. Google also provides other Internet services including e-mail, maps, social networking, and video sharing."]}

有没有办法制作一个包含精确定义的漂亮而整洁的字符串,仅此而已。顺便说一下,使用org.json库。

代码:

public class MainActivity {

private static String word;


public static void wordInitializer() throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    word = reader.readLine();
}

public static void processing() throws Exception {

    String path = "http://api.pearson.com/v2/dictionaries/ldoce5/entries?headword=" + word;        
    URL url = new URL(path);

    Scanner scanner = new Scanner(url.openStream());
    String line = "";
    while (scanner.hasNext())
        line += scanner.nextLine();
    scanner.close();

    JSONObject obj = new JSONObject(line);

    JSONObject results = obj.getJSONArray("results").getJSONObject(0);
    JSONArray senses = results.getJSONArray("senses");
    String definition = senses.getJSONObject(0).toString();
    System.out.println(definition);
}

public static void main(String[] args) throws Exception {
    wordInitializer();
    processing();
}

2 个答案:

答案 0 :(得分:1)

它是一个JSON数组,而不是String。方形括号可以解决这个问题。您应该将其解析为数组,然后获取第一个元素以获取定义。

答案 1 :(得分:0)

如果我们查看senses数组,我们会看到它包含一个对象,而该对象又有一个键definition,它也是一个数组。该数组中的第一个元素就是你想要的,你可以这样做:

String definition = senses.getJSONObject(0).getJSONArray("definition").getString(0);