Home >Java >javaTutorial >How to Extract a Specific Value from a JSON String Using Gson in Java?
Parsing JSON with Gson for Java
Objective:
Parse JSON data stored as a String using the Google Gson library and extract a specific value ("Hello world") from the JSON object.
Problem:
Given the following JSON data:
{ "data": { "translations": [ { "translatedText": "Hello world" } ] } }
and a Java class with a parse method:
public class JsonParsing { public void parse(String jsonLine) { // Extract the string "Hello world" from the JSON } }
Solution:
To parse the JSON, you can use Gson's JsonParser to obtain a JsonElement, which you can then cast to a JsonObject. Here's the code:
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 navigates the JSON object hierarchy using the getAsJsonObject and getAsJsonArray methods and ultimately retrieves the desired string value, "Hello world", which is stored in the "translatedText" property.
By leveraging the powerful data structure provided by Gson, you can easily parse and access specific data elements from complex JSON responses.
The above is the detailed content of How to Extract a Specific Value from a JSON String Using Gson in Java?. For more information, please follow other related articles on the PHP Chinese website!