Home > Java > javaTutorial > How to Extract Specific Values from Nested JSON Data using Google Gson in Java?

How to Extract Specific Values from Nested JSON Data using Google Gson in Java?

Mary-Kate Olsen
Release: 2024-12-17 22:59:11
Original
835 people have browsed it

How to Extract Specific Values from Nested JSON Data using Google Gson in Java?

Parsing JSON Data with Google Gson in Java

Problem:

Given a JSON string containing nested objects and arrays, how can we extract a specific value from it using Google Gson?

Solution:

1. Create a Gson Parser:

JsonParser parser = new JsonParser();
Copy after login

2. Parse the JSON String:

JsonElement element = parser.parse(jsonLine);
Copy after login

3. Navigate the JSON Structure:

Using getAsJsonElement, getAsJsonObject, and getAsJsonArray, navigate through the JSON structure to reach the target value:

JsonObject dataObject = element.getAsJsonObject().get("data").getAsJsonObject();
JsonArray translationsArray = dataObject.get("translations").getAsJsonArray();
Copy after login

4. Extract the Target Value:

Once at the desired object, retrieve the specific value using get and getAsString:

String translatedText = translationsArray.get(0).getAsJsonObject().get("translatedText").getAsString();
Copy after login

Example Code:

Based on the provided JSON line and class, here's how you can parse the desired value:

public String parse(String jsonLine) {
    JsonElement element = new JsonParser().parse(jsonLine);
    JsonObject translationsObject = element.getAsJsonObject().get("data").getAsJsonObject().get("translations").getAsJsonArray().get(0).getAsJsonObject();
    String translatedText = translationsObject.get("translatedText").getAsString();
    return translatedText;
}
Copy after login

Remember to handle potential exceptions and null values as needed, and tailor the code to your specific JSON structure.

The above is the detailed content of How to Extract Specific Values from Nested JSON Data using Google 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