Home >Java >javaTutorial >How to Extract 'Hello world' from a JSON String Using Gson in Java?

How to Extract 'Hello world' from a JSON String Using Gson in Java?

Susan Sarandon
Susan SarandonOriginal
2024-12-20 02:26:11485browse

How to Extract

Utilizing Gson to Parse JSON in Java

Q: Parsing JSON Data as a String with Gson

Given a JSON string jsonLine, the task is to extract the text "Hello world" using the Gson library. The provided class, JsonParsing, contains a parse method that should accomplish this task.

A: Gson's Facile JSON Parsing

The following code snippet demonstrates how to parse the JSON string using Gson:

public String parse(String jsonLine) {
    JsonElement jelement = new JsonParser().parse(jsonLine);
    JsonObject  jobject = jelement.getAsJsonObject();
    jobject = jobject.getAsJsonObject("data");
    JsonArray jarray = jobject.getAsJsonArray("translations");
    jobject = jarray.get(0).getAsJsonObject();
    String result = jobject.get("translatedText").getAsString();
    return result;
}

This code sequence parses the JSON string, navigating through the nested objects and arrays to retrieve the desired text. For clarity, exception handling and input validation have been omitted.

Gson's JavaDoc provides comprehensive documentation for further exploration of its capabilities.

The above is the detailed content of How to Extract 'Hello world' from a JSON String Using Gson in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn