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
Release: 2024-12-20 02:26:11
Original
484 people have browsed it

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template