To extract a token like accessToken
from a JSON string in Java, the most robust way is to use the Jackson library. Below is a simple example demonstrating this.
✅ Step 1: Add Jackson to Your Project
If you're using Maven, include the Jackson dependency:
xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.3</version> <!-- Use latest version if possible -->
</dependency>
✅ Step 2: Write Java Code to Extract the Token
java
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class TokenExtractor {
public String extractTokenFromResponse(String responseBody) throws Exception {
// Create an ObjectMapper instance
ObjectMapper objectMapper = new ObjectMapper();
// Parse the response string into a JsonNode
JsonNode jsonNode = objectMapper.readTree(responseBody);
// Extract the accessToken field from the JSON
return jsonNode.get("accessToken").asText();
}
public static void main(String[] args) {
String jsonResponse = "{\n" +
" \"accessToken\": \"eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxIiwic2...\"\n" +
"}";
TokenExtractor extractor = new TokenExtractor();
try {
String token = extractor.extractTokenFromResponse(jsonResponse);
System.out.println("Extracted Token: " + token);
} catch (Exception e) {
e.printStackTrace();
}
}
}
🔍 Explanation
- ObjectMapper: Jackson's main utility to convert JSON into Java objects.
- readTree(): Converts a JSON string into a
JsonNode
. - get("accessToken") + asText(): Retrieves and converts the
accessToken
field from the JSON.
✅ Output Example
text
Extracted Token: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxIiwic2...
This method is ideal for APIs returning authentication tokens in JSON format. You can then use this token in your authorization headers for subsequent API requests.